Object oriented programming in python

Object Oriented Programming: Object Oriented Programming, referred to as OOP, that is, object-oriented programming.

Class and object

Class is used to describe a collection of objects with the same properties and methods. An object is a concrete instance of a class.

For example, if students have names and scores, the names and scores are common attributes. At this time, a class can be designed to record students' names and scores.

Here we explain the properties and methods

  • Attribute: attribute, used to describe the public attributes of all objects, such as student's name and score.
  • Method: the function contained in the class is also called class function, which is different from the function outside the class. It is used to realize some functions, such as printing out the student's name and score.

Use the keyword class to create a class

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

In the above case, only a class is defined, and the computer does not create storage space.

Only after the instantiation of the class is completed can the specific object of the class be created and the storage space be allocated. So, an object is an instance of a class.
Next, to create an object, just add two lines of code

Student1 = Student('Anny','100')
Student2 = Student('Mike','90')

In this way, Student is the class, and student1 and student2 are the specific objects of the class created. When there is the above code, Python will automatically call the init initial self construction function to create a specific object. The keyword self is a very important parameter that represents the creation of the function itself.

Once you have created a concrete object, you can use student1 Name and student1 Score to obtain the student's name and score respectively, or you can directly call the method student1 Out() to get all the information.

Class variables and instance variables

Suppose you need to add a counter now. Every time you add a student, the counter will increase by 1.

This counter does not belong to a student, but belongs to a class attribute, so it is called a class.

The name and score belong to each student, so they are called instance variables, also known as object variables.
Normally, a counter is added in this way

class Student():

    number = 0

    def __init__(self,name,score):
        self.name = name
        self.score = score
        number = number + 1

    def show(self):
        print("%s: %s"%(self.name,self.score))

student1 = Student('Anny',100)
student2 = Student('Mike',90)

print(student1.name)

number here is a class variable, so it is placed outside the method. name and score are instance variables, so it is placed inside the method.

Class variables and instance variables are very different, and the access methods are also different.

Class variables: class variables. Class variables are common in the whole instantiated object. Class variables are defined in the class and outside the function. The specific method to access or call class variables is the class name Variable name, or self class. Variable name, self class. Automatically returns the class name of each object.
Instance variables: instance variables, variables defined in a function, belong to a specific object. The method to access or call instance variables is the object name Variable name, or self Variable name.

Execute the above code and you will find an error
UnboundLocalError: local variable 'number' referenced before assignment
It roughly means the task before the reference of the local variable number,
Therefore, if you want to call the variable number belonging to the class, you use student Number or self class. number

Amend as follows:

class Student():

    number = 0

    def __init__(self,name,score):
        self.name = name
        self.score = score
        Student.number = Student.number + 1

    def show(self):
        print("%s: %s"%(self.name,self.score))

student1 = Student('Anny',100)
student2 = Student('Mike',90)

student1.show()
print(student2.number)

Class method

Some variables only belong to classes, and some methods only belong to classes and do not belong to specific objects. It is not difficult to find that there are self parameters in the methods belonging to the object, such as init(self), show(self), etc. in the class, cls is used, which is similar to self. It represents the class itself and is generally illustrated by the modifier of @ classmethod.

Here, a custom class method is used to print the number of students

class Student():

    number = 0

    def __init__(self,name,score):
        self.name = name
        self.score = score
        Student.number = Student.number + 1

    def show(self):
        print("%s: %s"%(self.name,self.score))    @classmethod
    def people(cls):
        print("Altogether%s Students"%Student.number)

student1 = Student('Anny',100)
student2 = Student('Mike',90)

student1.show()
student2.show()
Student.people()

Private properties and private methods of class

Private properties and private methods in the class are double underlined__ At the beginning, private properties and methods cannot be used or accessed directly outside the class. Change the score into a private attribute, and then print(Student.score), you will find an error. However, no error will be reported when calling show. This is because show is a function in the class, so you can access private variables.

The same is true for private methods. It is worth noting that private methods must contain the self parameter as the first parameter.

In object-oriented programming, it is usually rare for external classes to directly access the properties and methods inside the class, but to provide some buttons outside to access its internal members to ensure the security of the program, which is called encapsulation.

@property
    def scores(self):
        print("The student's grade is%s"%self.score)

After adding the decorator, it can be called directly without parentheses.

Class inheritance

The biggest advantage of object-oriented programming is to avoid repeated code, that is, to reuse a piece of code. One of the methods is inheritance.

First define a base class or parent class, and then create a subclass through class name (parent class): pass. In this way, the subclass obtains all the properties and methods of the parent class. This phenomenon is called inheritance.

Write another piece of code. Use Schoolmember to represent the parent class. Name and age are the attributes of everyone. However, teachers have the exclusive attribute of salary and students have the exclusive attribute of score

# Create parent school memberclass schoolmember:

    def __init__(self, name, age):
        self.name = name
        self.age = age    def tell(self):
        # Print personal information
        print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")# Create a subclass teacher Teacherclass Teacher(SchoolMember):

    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age) # Initialization with parent class
        self.salary = salary    # Method rewrite
    def tell(self):
        SchoolMember.tell(self)
        print('Salary: {}'.format(self.salary))# Create subclass student Studentclass Student(SchoolMember):

    def __init__(self, name, age, score):
        SchoolMember.__init__(self, name, age)
        self.score = score    def tell(self):
        SchoolMember.tell(self)
        print('score: {}'.format(self.score))

teacher1 = Teacher("John", 44, "$60000")
student1 = Student("Mary", 12, 99)

teacher1.tell()  # Print Name:"John" Age:"44" Salary: $60000student1.tell()  # Name:"Mary" Age:"12" score: 99

It is not difficult to see from the above code

  • In the process of creating subclasses, you need to manually call the constructor init of the parent class to complete the creation of subclasses.
  • When you call a parent class in a subclass, you need to add the prefix of the parent class, and you must bring the self parameter variable. For example, schoolmember tell(self).
  • If a subclass calls each method or property, Python will first look for it in the parent class. If it cannot be found, it will look for it in the subclass.

==In a real project, a subclass can inherit multiple parent classes==

Use the super() keyword to call the parent class

In the subclass, you can use the super keyword to directly call the properties or methods in the parent class to simplify the code, which also reflects the short life. I use Python.

# Create subclass student Studentclass Student(SchoolMember):

    def __init__(self, name, age, score):
        SchoolMember.__init__(self, name, age)
        self.score = score    def tell(self):
        super().tell() # Equivalent to schoolmember tell(self)
        print('score: {}'.format(self.score))

In the above example, the student subclass calls the tell method of the parent class, which is equivalent to schoolmember Tell (self). When calling with the super keyword, remove the self in parentheses.

That's all for this sharing. If it's helpful to you, please pay attention before you go ~ thank you for reading.

Keywords: Python

Added by Nilpez on Wed, 22 Dec 2021 03:05:54 +0200