Class variables

1


class Person(object):
    kind = 'human'
    
    def __init__(self, name):
        self.name = name
    
    def who_are_you(self):
        print(self.name, self.kind)

p1 = Person('A')
p2 = Person('B')

p1.who_are_you()
p2.who_are_you()

Execution result of 1


A human
B human

The class variable (kind in this case) is It is shared by all the created objects.

2


class T(object):
    words = []
    
    def add_word(self, word):
        self.words.append(word)

c = T()
c.add_word('apple')
c.add_word('banana')
print(c.words)

d = T()
d.add_word('orange')
d.add_word('cake')
print(d.words)

Execution result of 2


['apple', 'banana']
['apple', 'banana', 'orange', 'cake']

I created two objects, an object called c and an object called d, Because words is a class variable It has been shared by c and d.

This can lead to bugs.

To prevent this Initialize (assign to an instance variable) with __init__ each time.

3


class T(object):
    def __init__(self):
        self.words = []
    
    def add_word(self, word):
        self.words.append(word)

c = T()
c.add_word('apple')
c.add_word('banana')
print(c.words)

d = T()
d.add_word('orange')
d.add_word('cake')
print(d.words)

Execution result of 3


['apple', 'banana']
['orange', 'cake']

Recommended Posts

Class variables
Class variables
class
class
Python: Class and instance variables
Globalization of class instance variables
Python class variables and instance variables
Landmines hidden in Python class variables
[Python] Variables
Class inheritance
How should I access class variables?
[Python] Inherit a class with class variables
Abstract class
[Python] class, instance
About python, class
[python] Difference between variables and self. Variables in class
Go class basics
Trouble with Python pseudo-private variables and class inheritance
Page processing class
Shell variables, environment variables
Class method static method
Python class, instance
Proprietary exception class
JSON conversion class
#Python basics (class)