我是 python 的新手,并试图弄清楚一个类是如何工作的,这是我的代码,它相当简单,但每当我运行它时,我都会收到 AttributeError: 'NoneType' object has no attribute 'arg1'。
class testclass:
def testmethod(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
p = testclass().testmethod("input1", "input2")
print(p.arg1)
我知道它现在已经发布了一百万次,但我就是想不通这个
当methods
的function
不要return
任何东西,通过default
它return
None
,当你做,你的情况:
p = testclass.testmethod('input', 'input'2)
您分配给p
变量None
是因为testmethod
不返回任何内容,如果您使用这种情况,您可以返回self
以获取self
object
.
class testclass:
def testmethod(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
return self
p = testclass().testmethod("input1", "input2")
print(p.arg1)
输出
input1
但我认为更好地使用constructor
,该__init__
方法。
class testclass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
p = testclass("input1", "input2")
print(p.arg1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句