简体   繁体   中英

Declare objects as an attribute of another object in python

I try to create a tree of objects / not classes. I mean i do not want to create relations between the objects in prototype level, but in instance level so the relations between the objects will be solved with the code.

Here i wrote something

class human :

    def  __init__ (self,Name,Surname,Gender,Age,Father,Mother) :

        self.Name = Name
        self.Surname = Surname
        self.Gender = Gender
        self.Age = Age
        self.Father = Father
        self.Mother = Mother

class family :

    def __init__ (self,Surname,Members) :

        self.Surname = Surname
        self.Members = Members

    def ListMembers (self) :

        for member in self.Members :

            print (self.Surname +' family member ' +member.Name + ' '+ member.Surname + ' is ' + member.Age + " years old ")


human1 = human( 'Mary','Walter','Female','42','Jason White','Sally White')
human2 = human('Charles', 'Walter', 'Male', '45', 'Samuel Ribbon', 'Angie Ribbon')
human3 = human('Claire', 'White', 'Female', '16', 'Charles Walter', 'Mary Walter')

WalterFamily = family('Walter',(human1,human2,human3))

WalterFamily.ListMembers

When i run this code WalterFamily.ListMembers prints nothing.

What is exact way of nesting objects in another object ? Like i tried to do here : Nesting 3 humans inside a family and also reach to the attributes of these objects..

The last line of code is not what you want. All functions that belong to a class (like your ListMembers function) is a function stored in a variable name.

When you have what you currently have:

WalterFamily.ListMembers

You only print the function object stored at the ListMembers variable. To actually call it, you need to add parenthesis.

WalterFamily.ListMembers()

In Python everything is an object, including functions. So WalterFamily.ListMembers is just a reference to the object. To call the function you need WalterFamily.ListMembers()

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