简体   繁体   中英

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)

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. I have checked "Similar Question" to no avail.

Thanks in advance!

Because you missed a return statement in the first printattr . In order to propagate the return value of printattr2 onwards from printattr you have to return the returned value :

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

Your printattr function has no return statement. Change

self.printattr2() 

to

return self.printattr2()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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