User Tools

Site Tools


python:class_instance_variables

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
python:class_instance_variables [2016/01/26 09:38]
admin
python:class_instance_variables [2016/01/26 10:23] (current)
Line 25: Line 25:
 === Examples === === Examples ===
  
 +Now a couple of examples to understand different behaviours:
 +
 +<code python | Shared class variable >
 +class Visitor:
 +    counter = 0
 +
 +    def __init__(self):​
 +        type(self).counter += 1
 +        # similar Visitor.counter but it doesn'​t help with inheritance
 +        ​
 +v1 = Visitor()
 +v2 = Visitor()
 +v3 = Visitor()
 +
 +print("​Final shared counter {} or {}"​.format(Visitor.counter,​ v2.counter))
 +# Displays: Final shared counter 3 or 3
 +</​code>​
 +
 +Using self, you can transform a class variable into an instance variable.\\ ​
 +The class variable will exist separately of the instance one.
 +
 +<code python | Transformed class variable>​
 +class Visitor:
 +    counter = 0
 +
 +    def __init__(self):​
 +        self.counter += 1
 +        # this is making the above counter variable - instance type 
 +        ​
 +v1 = Visitor()
 +v2 = Visitor()
 +v3 = Visitor()
 +
 +print("​Final shared counter {} or {}"​.format(Visitor.counter,​ v3.counter))
 +# Final shared counter 0 or 1
 +
 +print(Visitor.__dict__)
 +print(v1.__dict__)
 +</​code>​
 +
 +Mixing those two type will result in a strange behaviour for the programmer:
 +
 +<code python | Messing with variables type>
 +class Visitor:
 +    counter = 0
 +
 +    def __init__(self):​
 +        self.counter += 1
 +        ​
 +        ​
 +v1 = Visitor()
 +Visitor.counter = 100 
 +print("​Counter v1: {}"​.format(v1.counter)) # displays 1, v1 init already take place
 +
 +v2 = Visitor()
 +Visitor.counter = 200
 +print("​Counter v2: {}"​.format(v2.counter)) # displays 101 (previous 100 + 1)
 +
 +v3 = Visitor()
 +print("​Counter v1: {}"​.format(v3.counter)) # displays 201 (previous 200 + 1)
 +</​code>​
 +
 +Example with a different type of a shared variable:
 +
 +<code python | Using a list as shared variable>​
 +class Visitor:
 +    items = []
 +
 +    def __init__(self):​
 +        print("​Previous items: {}"​.format(self.items))
 +    ​
 +    def add_item(self,​ item_name):
 +        self.items.append(item_name)
 +        ​
 +
 +   
 +v1 = Visitor() ​ # displays Previous items: []
 +v1.add_item("​suit"​)
 +
 +v2 = Visitor() ​ # displays Previous items: ['​suit'​]
 +v2.add_item("​t-shir t")
 +
 +v3 = Visitor() ​ # displays Previous items: ['​suit',​ '​t-shirt'​]
 +v3.add_item("​pullover"​)
 +</​code>​
  
python/class_instance_variables.1453819092.txt.gz ยท Last modified: 2016/01/26 09:38 by admin