[英]Python: Classes, Methods, Parameter Attributes
I am rather new to using classes. 我对使用类很陌生。 I struggle with functions (ie methods) in classes and how to access the classes attributes via method parameter.
我对类中的函数(即方法)以及如何通过方法参数访问类属性感到困惑。
My aim is to have a method accessing an instance's list (and the instances contained therein, yadda yadda) 我的目标是要有一种方法来访问实例的列表(及其中包含的实例yadda yadda)
While: 而:
class dictclasser:
def __init__(self, attribute):
self.attribute = attribute
def printattr(self):
self.printattr2()
def printattr2(self):
return self.attribute
classcollection = []
while True:
attribute = input()
classcollection.append(dictclasser(attribute))
for i in classcollection:
print(i.printattr())
Returns None 不返回
class dictclasser:
def __init__(self, attribute):
self.attribute = attribute
def printattr(self):
return self.attribute
classcollection = []
while True:
attribute = input()
classcollection.append(dictclasser(attribute))
for i in classcollection:
print(i.printattr())
Returns everything as intended. 按预期返回所有内容。 I cannot figure out why printattr can access the instances attribute and printattr2 cannot.
我无法弄清楚为什么printattr可以访问实例属性而printattr2无法访问。 I have checked "Similar Question" to no avail.
我已检查“类似问题”,但无济于事。
Thanks in advance! 提前致谢!
Because you missed a return statement in the first printattr
. 因为您错过了第一个
printattr
的return语句。 In order to propagate the return value of printattr2
onwards from printattr
you have to return the returned value : 为了从
printattr
向前传播printattr2
的返回值,您必须返回返回值 :
def printattr(self):
return self.printattr2()
Your printattr function has no return statement. 您的printattr函数没有return语句。 Change
更改
self.printattr2()
to 至
return self.printattr2()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.