繁体   English   中英

Python:类,方法,参数属性

[英]Python: Classes, Methods, Parameter Attributes

我对使用类很陌生。 我对类中的函数(即方法)以及如何通过方法参数访问类属性感到困惑。

我的目标是要有一种方法来访问实例的列表(及其中包含的实例yadda yadda)

而:

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())

不返回

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())

按预期返回所有内容。 我无法弄清楚为什么printattr可以访问实例属性而printattr2无法访问。 我已检查“类似问题”,但无济于事。

提前致谢!

因为您错过了第一个printattr的return语句。 为了从printattr向前传播printattr2的返回值,您必须返回返回值

def printattr(self):
    return self.printattr2()

您的printattr函数没有return语句。 更改

self.printattr2() 

return self.printattr2()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM