Class Dog :
name = str()
trick = []
A = Dog()
B = Dog()
A.name = 'Apple'
B.name = 'Banana'
A.trick.append('say_hi')
B.trick.append('stand')
If you make a class like this, The names of A and B are saved as Apple and Banana, respectively.
Why is trick saved with 'say_hi' and 'stand'?
Is there any difference between name and trick?
python
>>> class Dog:
... ... name = str()
... ... trick = []
...
>>> A = Dog()
>>> B = Dog()
>>> A.name = 'Apple'
>>> B.name = 'Banana'
>>> A.trick.append('say_hi')
>>> B.trick.append('stand')
>>> A.__dict__['name']
'Apple'
>>> A.__class__.__dict__['name']
''
>>> A.__class__.__dict__['trick']
['say_hi', 'stand']
>>> A.__dict__['trick']
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
KeyError: 'trick'
>>> A.trick
['say_hi', 'stand']
Python manages variables in a dictionary.
Instance variables are stored in the dict field, and for class variables, class is added to provide access to the object.class.dict field.
You can see that trick works with the static keyword in Java or c++ (no instance variables), and for primitive types, if you created an instance, you can create an instance variable separately.
© 2024 OneMinuteCode. All rights reserved.