I'm curious about the Python class variable

Asked 2 years ago, Updated 2 years ago, 17 views

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

2022-09-21 19:50

1 Answers

>>> 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.


2022-09-21 19:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.