Chapter 13_ Object-oriented Advancement
Content overview:
1. Packaging
2. Inheritance
3. Method Rewrite
4. object class
5. Polymorphism
6. Special methods and special properties
1. Packaging
1. Three Object-Oriented Features
- Encapsulation: Enhance program security
- Wrap data (attributes) and behavior (methods) into class objects. Operate on attributes inside methods and call methods outside class objects. This isolates complexity by not caring about the implementation details within the method.
- There are no special modifiers in Python for the private use of attributes, and if the attribute does not want to be accessed outside the class object, use two''in front.
- Inheritance: Enhance code reuse
- Polymorphism: Improve program scalability and maintainability
2. Implementation of Encapsulation
#110. Three Object-Oriented Features_ Implementation of Encapsulation class Student: def __init__(self,name,age): self.name=name self.__age=age def show(self): print(self.name,self.__age) stu=Student('Zhang San',20) stu.show() #Use name and age outside of class print(stu.name) # print(stu.__age) #AttributeError: 'Student' object has no attribute '__age' # print(dir(stu)) print(stu._Student__age) #Outside the class, you can use _ Student_u Age for access
2. Inheritance
1. Inheritance Grammar
-
Grammar Format
class Subclass Class Name(Parent 1, Parent 2): pass
- If a class does not inherit any classes, the object is inherited by default
- When defining a subclass, the constructor of the parent class must be called in its constructor
2. Code implementation of inheritance
#111. Inheritance and its implementation 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) 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,teachofyear): super().__init__(name,age) self.teachofyear=teachofyear stu=Student('Zhang San',20,'1001') teacher=Teacher('Li Si',34,10) #Call info method of Person class (parent) in stu, teacher instance (subclass object), output name, age stu.info() teacher.info()
3. Multiple Inheritance
- Python supports multiple inheritance
3. Method Rewrite
-
override
- If a subclass is not satisfied with an attribute or method inherited from its parent, it can be rewritten in the subclass (method body)
- In a method overridden by a subclass, the overridden method in the parent class can be called by **super().xxx()**.
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) 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,teachofyear): super().__init__(name,age) self.teachofyear=teachofyear stu=Student('Zhang San',20,'1001') teacher=Teacher('Li Si',34,10) #Call info method of Person class (parent) in stu, teacher instance (subclass object), output name, age stu.info() teacher.info()
Above, in the left column:
Basket+White Arrow: Indicates that the parent method is overridden by the child method (shown in the parent method, pointing to the overridden child method)
Blue Circle + Orange Arrow: Represents an override of the parent method (shown in the subclass method, pointing to the overridden parent method).
4. object class
- object class
- The object class is the father of all classes, so all classes have properties and methods of the object class.
- The built-in function dir() allows you to view all the properties of a specified object
- Object has a u Str()u Method that returns a description of the object corresponding to the built-in function u Str()u It's often used in the print() method to help us see the information about the object, so we often look at u Str()u Rewrite
#113.object class class Student: def __init__(self,name,age): self.name=name self.age=age def __str__(self): return 'My name is{0},This year{1}Age'.format(self.name,self.age) stu=Student('Zhang San',20) print(dir(stu)) print(stu) #Direct Call_u str_u () such a method print(type(stu))
5. Realization of Polymorphism
- polymorphic
- Simply put, polymorphism means that even if you don't know what type of object a variable refers to, you can still invoke a method through this variable, which dynamically determines which method in that object is invoked at run time based on the type of object the variable refers to.
#114. Implementation of polymorphism class Animal(object): def eat(self): print('Animals eat') class Dog(Animal): def eat(self): print('Dogs eat bones...') class Cat(Animal): def eat(self): print('Cats eat fish...') class Person: #Inherit no class, inherit object by default def eat(self): print('People eat grains') #Define a function def fun(obj): obj.eat() #Start calling functions fun(Cat()) fun(Dog()) fun(Animal()) print('-----------------------') fun(Person()) #Python: Dynamic language that dynamically binds properties and methods after an object is created.
6. Static Language and Dynamic Language
- Differences between static and dynamic languages about polymorphism
- Three Requirements for Polymorphism in Static Languages
- inherit
- override
- Parent Reference Points to Subclass Object
- Three Requirements for Polymorphism in Static Languages
- Dynamic language polymorphism advocates the "duck type". When you see a bird walking like a duck, swimming like a duck, and gathering like a duck, it can be called a duck. In the duck type, it is not necessary to care about what kind of object it is, whether it is a duck or not, but only about the behavior of the object.
Python: Dynamic Language
Java: Static Language
7. Special methods and special attributes
1. Special Attributes
#115. Special Attributes #print(dir(object)) class A: pass class B: pass class C(A,B): def __init__(self,name,age): self.name=name self.age=age class D(A): pass #Create object of class C x=C('Jack',20) #x is an instance object of type C print(x.__dict__) #Property Dictionary of Instance Object print(C.__dict__) #Class object properties and method dictionary print('-------------------') print(x.__class__) #<class'u Main_u. C'>Outputs the class to which the object belongs print(C.__bases__) #Father type element of class C (output as tuple) print(C.__base__) #A base class of the output C class (near C) print('--------------------') print(C.__mro__) #Hierarchy of classes print(A.__subclasses__()) #List of subclasses
2. Special methods
#116. Special methods a=20 b=100 c=a+b #Addition of objects of two integer types d=a.__add__(b) #The underlying method of addition print(c) print(d) class Student: def __init__(self,name): self.name=name def __add__(self, other): return self.name+other.name stu1=Student('Zhang San') stu2=Student('Li Si') s=stu1+stu2 #The addition operation of two objects is implemented (because a special method of u add_() is written in the Student class) #By rewriting_u add_u () method, which can use custom objects, has the'+'function print(s) print('-----------------------------------') lst=[11,22,33,44] print(len(lst)) #Len is the content function len print(lst.__len__())
8. u new_u And u init_u Demonstrates the process of creating objects
#117. u New_u And u init_u Demonstrates the process of creating objects class Person(object): def __new__(cls,*args,**kwargs): #Creating objects print('__new__Called to execute, cls Of id Value is{0}'.format(id(cls))) obj=super().__new__(cls) print('Of the created object id For:{0}'.format(id(obj))) return obj def __init__(self,name,age): #(2) Initialization of the created object (assigning values to instance attributes of the object) print('__init__Called, self Of id Values are:{0}'.format(id(self))) self.name=name self.age=age print('object Of this class id For:{0}'.format(id(object))) print('Person Of this class id For:{0}'.format(id(Person))) #Create instance object of Person class p1=Person('Zhang San',20) #3. Store the created object in p1 print('p1 this Person Of the instance object of the class id: {0}'.format(id(p1)))
9. Shallow and deep copies of classes
1. Assignment of Variables
- Just two variables, actually pointing to the same object
2. Shallow copy
- Python copies generally clean up shallow copies. When you copy, the object contains no copies of the child object content, so the source object and the copy object refer to the same child object
Computer has a different id than computer2, but it points to the same address as the instance object.
3. Deep copy
- Using the deepcopy function of the copy module, the child objects contained in the recursive copy object, the source object, and all the child objects of the copy object are different
#118. Class assignment and shallow copy class CPU: pass class Disk: pass class Computer: def __init__(self,cpu,disk): self.cpu=cpu self.disk=disk #(1) Assignment of variables cpu1=CPU() cpu2=cpu1 print(cpu1,id(cpu1)) print(cpu2,id(cpu2)) #(2) class has shallow copy print('-------------------------') disk=Disk() #Create an object of a hard disk class computer=Computer(cpu1,disk) #Create an object of a computer class #shallow copy import copy computer2=copy.copy(computer) print(computer,computer.cpu,computer.disk) print(computer2,computer2.cpu,computer2.disk) print('----------------------------------------') #deep copy computer3=copy.deepcopy(computer) print(computer,computer.cpu,computer.disk) print(computer3,computer3.cpu,computer3.disk)