I was reading the official Python tutorial about class and instance variables and found the following code snippet very hard to understand. Can someone kindly help me out?
In section 9.3.5 of this link ( https://docs.python.org/3.8/tutorial/classes.html ), it talks about being cautious when using mutable object as class variables. It gives an example which is the wrong way to do it by using list as a class variable. I understand the difference between class variable and instance variable. However, I'm very perplexed about the syntax.
class Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
My question is in the "add_trick" function definition, shouldn't prefixing "tricks" with "self" introduce an instance list variable "tricks"? And since it hasn't been initialized to [], shouldn't it generate an error? Of course, the code runs without an error.! Below is what I would have written based on my understanding but it generates error.
class Dog:
tricks = [] # define a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
tricks.append(trick) # remove self to make it clear its a class variable.
You can't use the bare name tricks
to refer to a class variable. If you wanted to you could name the class explicitly ( Dog.tricks
), but you get the same result going through self
.
Using self.tricks
only creates an instance variable if you're assigning to the attribute directly. If you're mutating an existing class variable, accessing it through self
doesn't change it into an instance variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.