Strange Python behavior - or am I missing something

The following code:

class House: links = [] class Link: pass class Villa(House): pass if __name__ == '__main__': house = House() villa = Villa() link = Link() house.links.append(link) print house.links print villa.links 

leads to this result:

 [<__main__.Link instance at 0xb65a4b0c>] [<__main__.Link instance at 0xb65a4b0c>] 

I find it very strange: since this is another example? - I would expect that there will be a conclusion - since this is a different instance ?:

 [<__main__.Link instance at 0xb65a4b0c>] [] 

When you change the line house.links.append(link) to house.links = [link] everything works as expected.

Can someone explain this behavior?

+4
source share
2 answers

This is a different instance, but you defined links as a class variable, not an instance variable.

An instance variable will be defined as such:

 class House(object): # Always use new-style classes except for backward compatibility def __init__(self): self.links = [] 

Note that in Python, unlike other languages, an instance variable is explicitly declared as an instance property. This usually happens in the __init__ method to ensure that each instance has a variable.

Then the subclass will look like this:

 class Villa(House): def __init__(self): super(Villa, self).__init__() 

And code execution gives the correct results:

 >>> house = House() >>> villa = Villa() >>> link = Link() >>> house.links.append(link) >>> print house.links [<__main__.Link instance at 0xcbaa8>] >>> print villa.links [] 
+19
source

In your code, links is an attribute of a class, which makes it common to all instances of this class:

 class House: links = [] 

Because of this, your Villa class shares this attribute because the Villa instance is (as a subclass of) also an instance of House .

If you want to make a link instance variable, write a constructor and set links as a self attribute, for example.

 class House: def __init__(self): self.links = [] 
+3
source

Source: https://habr.com/ru/post/1315451/


All Articles