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

2017-07-03 19:49:13 +08:00
 saximi
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'
1471 次点击
所在节点    Python
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'


楼主你自己的代码需要传递实例

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/372759

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX