python -- three characteristics of object oriented

Posted by Niko on Wed, 26 Jan 2022 23:58:45 +0100

Three characteristics of object oriented

Encapsulation: improve program security

  • Wrap data (properties) and behavior (Methods) into class objects. Operate on attributes inside the method and call methods outside the class object. In this way, there is no need to care about the specific implementation details inside the method, thus isolating the complexity.
class Car:
    def __init__(self,brand):
        self.brand=brand
    def start(self):
        print('The car has started')

car=Car('Benz')
car.start()
print(car.brand)
#Wrap data (properties) and behavior (Methods) into class objects. Operate on attributes inside the method and call methods outside the class object. In this way, there is no need to care about the specific implementation details inside the method, thus isolating the complexity.
  • ·In Python, there is no special modifier for the private of the attribute. If the attribute does not want to be accessed outside the class object, the first two "" are used.
class Student:
    def __init__(self,name,age):
        self.name=name
        self.__age=age  #Age doesn't want to be used outside the class, so two are added_
    def show(self):
        print(self.name,self.__age)

stu=Student('Zhang San',20)
stu.show()

#Use name and age outside the class
print(stu.name)
#The attribute print (stu. _age) is not intended to be used externally
#print(dir(stu))
print(stu._Student__age) #Outside the class, you can_ Student__age for access

Inheritance: improve code reusability

Syntax format

class Subclass class name (Parent 1, parent 2...)
    pass
  • If a class does not inherit any classes, it inherits object by default
  • When defining a subclass, the constructor of the parent class must be called in its structure function.
class Person(object): #Person inherits object class
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print(self.name,self.age)
#Define subclasses
class Student(Person):
    def __init__(self,name,age,stu_no):
        super().__init__(name, age)
        self.stu_no=stu_no

class Teacher(Person):
    def __init__(self,name,age,teachofvear):
        super().__init__(name,age)
        self.teachofvear=teachofvear

stu=Student('Zhang San',20,'1001')
teacher=Teacher('Li Si',34,10)

stu.info()
teacher.info()
  • python supports multiple inheritance
class A(object):
    pass

class B(object):
    pass

class C(A,B):
    pass
#C has two parent classes, A and B


Polymorphism: improve program scalability and maintainability

In short, polymorphism means "having multiple forms". It means that even if you don't know the type of object referenced by a variable, you can still call methods through this variable. During the running process, you can dynamically decide which method in the object to call according to the type of object referenced by the variable

The difference between static language and dynamic language about polymorphism

Three necessary conditions for static language to realize polymorphism

  • inherit
  • Method rewrite
  • A parent class reference points to a child class object

If static language wants to realize polymorphism, it must clarify the inheritance relationship

The polymorphism of dynamic language advocates "duck type". When a bird looks like a duck, swims like a duck and walks like a duck, the bird can be called a duck. In duck type, you don't need to care about what type the object is or whether it is a duck. You only care about the behavior of the object. Python is a dynamic language

class Animal(object):
    def eat(self):
        print('Animals can eat')
class Dog(Animal):
    def eat(self):
        print('Dogs eat bones...')
class Cat(Animal):
    def eat(self):
        print('Cats eat fish...')

class Person:
    def eat(self):
        print('People eat cereals')

#Define a function
def fun(obj):
    obj.eat()

#Start calling function
fun(Cat())
fun(Dog())
fun(Animal())

fun(Person())

Method rewrite

  • If a subclass is not satisfied with a property or method inherited from the parent class, it can rewrite it (method body) in the subclass
  • Subclass overridden methods can be overridden through super() Xxx() calls the overridden method in the parent class
class Person(object): #Person inherits object class
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print(self.name,self.age)
#Define subclasses
class Student(Person):
    def __init__(self,name,age,stu_no):
        super().__init__(name, age)
        self.stu_no=stu_no

    def info(self):  # Method rewrite
        super().info()
        print(self.stu_no)

class Teacher(Person):
    def __init__(self,name,age,teachofvear):
        super().__init__(name,age)
        self.teachofvear=teachofvear

    def info(self):
        super().info()
        print('Teaching age',self.teachofvear)

stu=Student('Zhang San',20,'1001')
teacher=Teacher('Li Si',34,10)

stu.info()
teacher.info()

object class

  • The object class is the parent class of all classes, so all classes have the properties and methods of the object class.
  • The built-in function dir() can view all properties of the specified object
  • Object has a_ str_ () method, which is used to return a description of the "object", corresponding to the built-in function str(), which is often used in the print() method to help us view the information of the object, so we often_ str_ () Rewrite
class Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
        return 'My name is{0},this year{1}year'.format(self.name,self.age)

stu=Student('Zhang San',20)
print(dir(stu))
print(stu)  #Called by default__ str__ () such method
print(type(stu))

Special methods and properties

namedescribe
Special properties__dict__Gets a dictionary of all properties and methods bound to a class object or instance object
Special method__len__()By rewriting__ len__ () method, so that the parameters of the built-in function len() can be user-defined types
__add__()By rewriting__ add__ () method, user-defined object can be used, with "+" function
__new__()Used to create objects
__init__()Initialize the created object
class A:
    pass

class B:
    pass

class C(A,B):
    def __init__(self,name,age):
        self.name=name
        self.age=age

#Create objects of class C
x=C('Jack',20)     #x is an instance object of type C
print(x.__dict__)   #Attribute dictionary of instance object
print(C.__dict__)   #Dictionary of C attributes

print(x.__class__)  #<class '__ main__. C '> outputs the class to which the object belongs
print(C.__bases__)  #Tuples of the parent type of class C
print(C.__base__)   #Base class of class
print(C.__mro__)    #View the hierarchy of classes
print(A.__subclasses__())   #List of subclasses

Topics: Python Back-end