Notes on learning python: object oriented, blooming in spring

1, Overview of object oriented

Object oriented is a systematic way of thinking according to people's understanding of the objective world, which decomposes the problem affairs into various objects. The purpose of establishing objects is not to complete a step, but to describe the behavior of something in the whole step of solving problems.

1. Category

Abstractions of objects with the same properties (data elements) and behaviors (functions) are classes. Therefore, the abstraction of an object is a class, and the materialization of a class is an object. In other words, an instance of a class is an object, and a class is actually a data type. Class has property, which is the abstraction of object state, and describes the property of class with data structure. Class has an operation, which is an abstraction of the behavior of an object. It is described by the operation name and the method to implement the operation. In short, a class is the soul of an object.

# Class definition, python development specification PEP8
# Hump nomenclature: StudentCount
class People:
    # Attribute, usually a noun
    # Class properties
    country = 'china'
    city = 'xian'

    # 1). __init__ It's called construction method. It doesn't work with ordinary methods. It will be executed automatically (when instantiating objects)
    # 2) What is self? In fact, it is an instantiated object
    # 3) . encapsulation
    def __init__(self, name, age):
        print('Executing constructor.....')
        print('self:', self)
        # Instance properties
        self.name = name  # self.name is the process of binding objects and properties together
        self.age = age

    # Method is usually a verb
    def coding(self):
        print('%s Programming in progress......' % (self.name))

2. Objects

The meaning of object refers to a specific thing, that is, things that can be seen and touched in real life. In object-oriented programming, object refers to a component of computer system. In object-oriented programming, object contains two meanings, one is data, the other is action. Object is a combination of data and action. Object can not only operate, but also record the operation results in time.
An object is an actual class, or an instantiated class

Instantiation refers to the process of creating objects with classes in object-oriented programming. Is an abstract concept class, specific to the process of this kind of physical. The instantiation process is generally composed of class name, object name = class name (parameter 1, parameter 2... Parameter n)

 # Object (instantiated object)
 p1 = People()
 print('class People:',People)
 print('object p1:',p1)
 print(p1.city)
 print(p1.country)
 p1.coding()

The relationship between class and object is just like decoration drawing and decoration room

2, Object oriented features

1. Package

Encapsulation is the combination of abstract data and behavior (or function) to form an organic whole (class); The purpose of encapsulation is to enhance security and simplify programming. Users don't need to know the specific implementation details, but only use the class members through the external interface and a specific access right.
Therefore, when using object-oriented encapsulation features, you need to:
1) . encapsulate content somewhere
2) . call encapsulated content from somewhere
1) . call the encapsulated content directly through the object: object. Property name
2) . indirectly call the encapsulated content through self: self. Attribute name
3) . indirectly call the encapsulated content through self: self. Method name ()

# Class definition, python development specification PEP8
# Hump nomenclature: StudentCount
class People:
    # Attribute, usually a noun
    # Class properties
    country = 'china'
    city = 'xian'

    # 1). __init__ It's called construction method. It doesn't work with ordinary methods. It will be executed automatically (when instantiating objects)
    # 2) What is self? In fact, it is an instantiated object
    # 3) . encapsulation
    def __init__(self, name, age):
        print('Executing constructor.....')
        print('self:', self)
        # Instance properties
        self.name = name  # self.name is the process of binding objects and properties together
        self.age = age

    # Method is usually a verb
    def coding(self):
        print('%s Programming in progress......' % (self.name))

Note: construction method__ init__ Unlike other common methods, when an object is created, the constructor is called immediately. Automatically execute the contents of the constructor

For object-oriented encapsulation, in fact, it is to encapsulate the content into the object by using the construction method, and then obtain the encapsulated content directly or indirectly through the object

2. Inheritance

Inheritance describes the relationship between things. When we define a class, we can inherit from an existing class. The new class is called a subclass or a subclass, while the inherited class is called a base class, a parent class or a superclass.

Inheritance characteristics

  • When a subclass inherits and defines a class, the name of the parent class is in parentheses ()
  • The properties and methods of the parent class will be inherited to the child class. For example, if the subclass is not defined__ init__ Method, the parent class has, that
    When the subclass inherits the parent class, this method is inherited, so as long as the object is created, the inherited method is executed by default__ init__ method
  • Overriding parent class method: in a subclass, there is a method with the same name as the parent class, and the method in the subclass will override the method with the same name in the parent class
    Example:
# Parent class (base class)
class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def get_grade(self):
        if 90 <= self.score <= 100:
            return 'A'
        else:
            return 'B'

    def learning(self):
        print('8:00 every morning-18: 00 Start learning')


# The subclass ComputerStudent inherits the Student parent
class ComputerStudent(Student):
    def get_grade(self):
        if 70 <= self.score <= 100:
            return 'A'
        else:
            return 'B'

    def learning(self):
        # 3) Call the method of the parent class: find the parent class of the ComputerStudent and execute the learning method of the parent class
        super(ComputerStudent, self).learning()
        print('   - operating system')
        print('   - computer network')
        print('   - Computer composition')
        print('   - Data structure and algorithm')


# The subclass MathStudent inherits the Student parent
class MathStudent(Student):
    def learning(self):
        # 3) Call the method of the parent class: find the parent class of MathStudent and execute the learning method of the parent class
        super(MathStudent, self).learning()
        print('   - Advanced mathematics')
        print('   - linear algebra')


# s = Student('zhang San ', 100)
# print(s.name, s.score, s.get_grade())

# 1) . inheritance rule: you have your own way_ The grade method performs its own get_grade method
s1 = ComputerStudent('Li Si', 80)
print(s1.get_grade())  # A
s1.learning()
# print(s1.aa())   # It will not be implemented

# 2) . inheritance rule: you don't get_ The grade method performs the get of the parent class_ Grade method
s2 = MathStudent('Zhang San', 80)
print(s2.get_grade())  # B
# print(s1.aa())   # It will not be implemented
s2.learning()

Multiple inheritance

Multiple inheritance means that a subclass has multiple parents and has their own characteristics
Note: succession at one level is multiple inheritance
Example:

class Base(object):
    def play(self):
        print('Base is playing!')


class A(Base):  # Inherit Base
    def play(self):  # Automatically override this method of the parent class
        print('A is playing')


class B(Base):  # Inherit Base
    def play(self):
        print('B is playing')


class C(B, A):  # Inherit A,B
    pass

c = C()
c.play()

result:

Note: from the method call of class C instance, when inheriting multiple parent classes, if there are the same methods in the parent class, then the child class will give priority to the method inherited first

Private properties and methods

  • By default, attributes are "public" in Python, and most OO languages provide "access control characters" to restrict the access of member functions.
  • In Python, if the variable name of an instance is__ At the beginning, it becomes a private variable / property. If the function name of the instance is__ At the beginning, it becomes a private function / method, which can only be accessed internally but not externally.
  • Note: subclasses cannot directly call private methods and properties of the parent class.

Example:

# Parent class (base class)
class Student:
    def __init__(self, name, score):
        self.name = name
        self.__score = score  # 1) . private property

    def get_grade(self):
        if 90 <= self.__score <= 100:  # 1) Class can access the private property self__ Score (eg: subclass not accessible)
            return 'A'
        else:
            return 'B'

    def set_score(self, score):
        self.__score = score

    def __play_game(self):  # 3) . private method
        print('I'm playing a game')


s = Student(name='Zhang San', score=100)
print(s.get_grade())
# print(s.__score)     # 1) Private properties cannot be accessed outside of. Class
s.set_score(80)
print(s.get_grade())  # 2) If you want to modify private properties, you can provide the method set_score is modified inside the class

Subclass calls private properties and methods of the parent class:

class aa:  # Define parent class aa
    def __init__(self):
        self.__u = 10  # Parent private data field
    def __m1(self):    # Parent private method
        self.__u += 1
        print(self.__u)

class bb(aa):  # Define subclass bb
    def m2(self):  # Access parent private data field
        self._aa__u = -10
        print(self._aa__u)
    def m3(self):  # Access to parent private methods
        self._aa__m1()
        
p = bb()
p.m3()  # Print 11
p.m2()  # Print - 10

3. Polymorphism

Polymorphism literally means "multiple states.". In object-oriented language, many different ways of interface implementation are called polymorphism. Generally speaking, the same operation acts on different objects, which can have different interpretations and produce different execution results.

The advantage of polymorphism is that when we need to pass in more subclasses, we only need to inherit the parent class, and the method can not be overridden directly (that is, it uses the parent class), or it can override a unique method. That's what polymorphism means. Callers only call, regardless of details. When we add a new subclass, we just need to make sure that the new method is written correctly, regardless of the original code. This is the famous "open close" principle

  • Open for extension: allows subclasses to override method functions
  • Closed for modification: do not override, inherit the function of the parent class directly
class Animal():
    def who(self):
        print("I am an Animal")
class Duck(Animal):
    def who(self):
        print("I am a duck")

class Dog(Animal):
    def who(self):
        print("I am a dog")

class Cat(Animal):
    def who(self):
        print("I am a cat")

def func(obj):
    obj.who()

if __name__ == "__main__":
    duck=Duck()
    dog=Dog()
    cat=Cat()
    func(duck)
    func(dog)
    func(cat)

There are two premises to realize polymorphism

  • 1. Inheritance: polymorphism must occur between parent class and child class
  • 2. Override: subclasses override parent methods

Tags: Python encapsulation Polymorphism Class

Posted by hcspider on Fri, 25 Jun 2021 06:39:22 +0930