What does self in class in Python mean?
大家讲道理
大家讲道理 2017-06-15 09:21:25
0
2
1099
def __init(self)

What does this self mean:?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
三叔

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?

过去多啦不再A梦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template