self represents oneself, self.name='xxx', which means that the name attribute value of this class is 'xxx', def _init_(self):xxxx is a method that will be automatically executed when creating an instance of this class. And def test(self):xxxx means that the methods you can call include self.test(). Do you understand this?
self refers to the object you will reference, which is slightly different during initialization and when calling the method. For example
class A:
def __init__(self, name):
self.name = name
def printname(self):
print(self.name)
a = A('hello')
a.printname()
When initializing the object,
self refers to this newly created object, so a is assigned to self, then self.name is equivalent to a.name, so the object a is created An attribute name. When calling a method: self refers to the object you want to reference, which is the object you want to act on, that is, a. So self is assigned the value a. So print(self.name) is equivalent to print(a.name).
Books:
Python Learning Manual has a very detailed explanation.
self represents oneself, self.name='xxx', which means that the name attribute value of this class is 'xxx', def _init_(self):xxxx is a method that will be automatically executed when creating an instance of this class. And def test(self):xxxx means that the methods you can call include self.test(). Do you understand this?
When initializing the object,self
refers to the object you will reference, which is slightly different during initialization and when calling the method. For exampleself
Books:refers to this newly created object, so
ais assigned to
self, then self.name
is equivalent to
a.name, so the object
ais created An attribute
name.
When calling a method:self
refers to the object you want to reference, which is the object you want to act on, that is,
a. So
selfis assigned the value
a. So print(self.name)
is equivalent to
print(a.name).
Python Learning Manual has a very detailed explanation.