A detailed explanation of the usage of class instance and self in Python

  • 2021-07-01 07:57:24
  • OfStack

1. Classes and instances of Python

In object-oriented, the most important concepts are class (class) and instance (instance). Class is an abstract template, while instance is a concrete "object" created according to class.

For example, students are an abstract concept with many attributes, which can be described by an Student class. Students' scores, heights and other attributes can be defined in the class, but there is no specific value. The instances are specific objects created by the class, and each object inherits the same method from the class, but the attribute values may be different. For example, if a student named hansry is created with a score of 93 and a height of 176, the instance has a specific value.

1. Class: Take the Student class as an example. In Python, the class is defined as follows:


class Student ( object ): 
  def __init__(self,name,score):
    self.name=name
    self.score=score

a. (object) indicates which class the class inherits from, while the object class is one class that each class inherits from. yt

b. The first parameter of the __init__ method is always self, which is used to represent the instance itself created by the class. Therefore, within the __init__ method, various attributes can be bound to self, because self itself points to the created instance itself.

c. With the __init__ method, when creating an instance, you cannot pass in empty parameters, but you must pass in parameters matching the __init__ method, but self itself does not need to pass in parameters, only the parameters after self.

2. Instance: After the class is defined, you can create an instance of Student through the Student class, which is realized by the class name + ():


student = Student ( 'name', 93 ) 

>>> student.name
"name"
>>> student.score
93

a. Where Student is the class name and ('name', 93) is the parameter to pass in

b. self. name are property variables of the Student class and are owned by the Student class. At the same time, name is an externally transmitted parameter, which is not included with the Student class. Therefore, self. name = name means that the value of the externally transmitted parameter name is assigned to its own attribute variable self. name of Student class.

3. There is only one difference between defining a function in a class and ordinary functions, that is, the first parameter is always the instance variable self of the class itself, and it does not need to be passed when calling. Besides, the methods (functions) of classes are no different from ordinary functions. You can use default parameters, variable parameters or keyword parameters.

2. Access to classes and instances

1. Restrict external access to class instance properties

Since the Student class instance itself has the data of these attributes, to access these data, it is not necessary to access them from outside functions, but you can define functions to access the data inside the class, so that you can encapsulate the "data". These functions that encapsulate data are associated with the Student class itself and are called methods of the class:


class Student(obiect):
  def __init__(self, name, score):
    self.name = name
    self.score = score
  def print_score(self):
    print "%s: %d" % (self.name, self.score)

>>> student= Student("hansry",99)
>>> student.print_property()

hansry:99

Thus, looking at the Student class from the outside, we only know that creating an instance requires giving name and score. How to print is defined internally in the Student class. These data and logic are encapsulated, and the call becomes easy, but the details of the internal implementation are unknown.

If you don't want internal attributes in the instance to be accessed by external attributes, change name and score to __name and __score, as shown in the following code:


class Student(object):

  def __init__(self, name, score):
    self.__name = name
    self.__score = score
  def print_property(self):
    print "%s: %d" %(self.__name,self.__score)

>>> student= Student("hansry",99)
>>> student.print_property()
>>> student.__name()

hansry:99
Traceback (most recent call last):
AttributeError: 'Student' object has no attribute '__name'

2. Open API so that external code can access the properties inside and modify them

External code accesses the class instance property, and the code is as follows:


  def __init__(self,name,score):
    self.__name=name
    self.__score=score
  def print_property(self):
    print("%s:%d"%(self.__name,self.__score))

  def get_name(self):
    return self.__name

  def get_score(self):
    return self.__score 

name=student.get_name()
score=student.get_score()
print ("%s , %d" % (name,score))

External code modifies the instance properties in the class, and the code is as follows:


  def __init__(self,name,score):
    self.__name=name
    self.__score=score
  def print_property(self):
    print("%s:%d"%(self.__name,self.__score))

  def reset_name(self , change_name):
    self.__name = change_name

  def reset_score(self, change_score):
    self.__score = change_score 

student= Student("hansry",99)
student.print_property()
student.reset_name("simona")
student.reset_score(91)
name=student.get_name()
score=student.get_score()
print ("%s:%d" % (name,score))

hansry:99
simona:91

It should be noted that in Python, variables whose names are similar to _xxx_, that is, those that start with double underscores and end with underscores, are special variables, which can be accessed directly, not private variables, and cannot be used with __name__ or __score__.

3. Careful use of self

1. self represents an instance of a class, not a class.


student = Student ( 'name', 93 ) 

>>> student.name
"name"
>>> student.score
93
0

student = Student ( 'name', 93 ) 

>>> student.name
"name"
>>> student.score
93
1

As can be seen from the above example, self represents only an instance of the class, while self.__class__ is the class.

2. When defining a class, self is best written, because it represents an instance of the class.

3. When inheriting, the passed-in instance is the passed-in instance, not the instance of the class that defines self.


student = Student ( 'name', 93 ) 

>>> student.name
"name"
>>> student.score
93
2

teacher=Teacher("hansry")
student=Student("simona")
student.print_self_1()
student.print_self()

hansry
simona
<__main__.Student object at 0x7fd9095b0950>
<__main__.Student object at 0x7fd9095b0950>

When running student.print_self (), the print_self () function of class Teacher is called. Although the function of class Teacher is called at this time, the instance self at this time is indeed generated when the class Student is instantiated.


Related articles: