Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve an attribute from a list of instances properly

I am unsure how to correctly get the attribute from a list of instances. Sorry if this seems simple, I am only a beginner.

class Clown:
    def __init__(self,name,hours,job):
        self.name = name
        self.hours = hours
        self.job = job
        
    def get_job(self):
        return self.job
    
    def change_job(self, new_job):
        self.job = new_job
        

list_of_clowns = [Clown("Tom",3,"puppets"), Clown("Jeff",1,"ballon animals")]

clown1 = Clown("Andy",4,"unicycle")


print(list_of_clowns[0].get_job) #problem

print(clown1.get_job()) #this works and prints "unicycle"

When I use
print(list_of_clowns[0].get_job)
it gives
<bound method Clown.get_job of <__main__.Clown object at 0x000001CE928DE20>>
when I want
puppets

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

By printing list_of_clowns[0].get_job you’re printing the definition of the method def get_job(self):.

Changing it to list_of_clowns[0].get_job() (note the parentheses), you will execute the method that than will return puppets.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading