search

Home  >  Q&A  >  body text

What does self in class in Python mean?

def __init(self)

What does this self mean:?

大家讲道理大家讲道理2760 days ago1121

reply all(2)I'll reply

  • 三叔

    三叔2017-06-15 09:23:25

    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?

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-15 09:23:25

    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.

    reply
    0
  • Cancelreply