推荐学习书目
› 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 · Jul 3, 2017 · 2157 views
    This topic created in 3378 days ago, the information mentioned may be changed or developed.
    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  
       Jul 3, 2017
    给楼主贴一段代码吧

    #!/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'


    楼主你自己的代码需要传递实例
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2302 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:11 · PVG 18:11 · LAX 03:11 · JFK 06:11
    ♥ Do have faith in what you're doing.