V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
saximi
V2EX  ›  Python

请教一个 getattr 的问题,感谢!

  •  
  •   saximi · 2017-07-03 19:49:13 +08:00 · 1467 次点击
    这是一个创建于 2508 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class A:
    def __init__(self):
    self.name = 'test'
    def method(self):
    print("method print")

    Instance = A()
    print(getattr(A, 'method', 'default')())


    上面这段代码输出如下,请问要怎么修改才能使得 print 语句可以显示 method 函数的执行结果呢?谢谢

    Traceback (most recent call last):
    File "d:\Python3\t1.py", line 9, in
    print(getattr(A, 'method', 'default')())
    TypeError: method() missing 1 required positional argument: 'self'
    zhusimaji
        1
    zhusimaji  
       2017-07-03 23:42:00 +08:00
    给楼主贴一段代码吧

    #!/usr/bin/python

    class test:
    def method(self):
    print('hello world')
    a=test()
    print(getattr(a,'method','default')())
    print(getattr(test,'method','default')())


    输出结果

    hello world
    None
    Traceback (most recent call last):
    File "/usercode/file3.py", line 8, in <module>
    print(getattr(test,'method','default')())
    TypeError: method() missing 1 required positional argument: 'self'


    楼主你自己的代码需要传递实例
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3332 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:49 · PVG 21:49 · LAX 06:49 · JFK 09:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.