Encapsulation, Inheritance and Polymorphism
Object-oriented programming has three important features: encapsulation, inheritance, and polymorphism.
encapsulation
Encapsulation refers to placing data and the implementation code of specific operations inside an object so that the details of the implementation of these codes are not discovered by the outside world. The outside world can only use the object through the interface, but can not modify the internal implementation of the object in any way. This is precisely because of the encapsulation mechanism.Programs do not need to care about the details of the object's data structure and how to implement operations when using it.Encapsulation can hide object implementation details, make code easier to maintain, and ensure system security to a certain extent because private information inside the object cannot be directly invoked or modified.Classes achieve a higher level of encapsulation than functions by encapsulating functions and variables internally.
class Student: room = '101' address = 'changsha' def __init__(self, name, age): self.name = name self.age = age def print_age(self): print('%s: %s' % (self.name, self.age)) # The following are incorrect uses # Class encapsulates its internal variables and methods to prevent direct external access print(room) print(adress) print_age()
Click for a complete set of Python zero Basics
inherit
Inheritance comes from the real world. One of the easiest examples is that children have some characteristics of their parents, that is, each child will inherit some of the characteristics of their father or mother. Of course, this is only the most basic inheritance relationship. There are more complex inheritance in the real world.The inheritance mechanism enables code reuse, where parts of code common to multiple classes can be provided in only one class, whereas other classes simply need to inherit this class.
The greatest benefit of inheritance is that while a subclass obtains all the variables and methods of the parent class, it can also be modified and expanded as needed.Its grammatical structure is as follows:
class Foo(superA, superB,superC....): class DerivedClassName(modname.BaseClassName): ## When the parent class is defined in another module
Python supports multiple inheritance mechanisms of parent classes, so it is important to note the order of base classes in parentheses. If the base class has the same method name and is not specified when using a subclass, Python will search left to right for the inclusion of the method in the base class.Once found, call it directly, and don't continue searching later.
# Parent Class Definition class people: def __init__(self, name, age, weight): self.name = name self.age = age self.__weight = weight def speak(self): print("%s say: I %d Age." % (self.name, self.age)) # Single Inheritance Example class student(people): def __init__(self, name, age, weight, grade): # Call the instantiation method of the parent class people.__init__(self, name, age, weight) self.grade = grade # Override the speak method of the parent class def speak(self): print("%s say: I %d Aged, I'm reading %d grade" % (self.name, self.age, self.gra de)) s = student('ken', 10, 30, 3) s.speak()
Inheritance mechanism of Python3
Python3 has a different inheritance mechanism than Python2.Its core principles are the following two, please keep in mind!
-
When a subclass calls a method or variable, it first looks within itself, and if it cannot find it, it starts looking within the parent according to the inheritance mechanism.
-
Find the parent class one by one in a depth-first manner, according to the order in the parent class definition!
super() function
We all know that if there is a member in a subclass with the same name as the parent class, that member in the parent class will be overwritten.So what if you want to force members of the parent class to be called?Use the super() function!This is a very important function, most often by calling the instantiation method of the parent class through super:
__init__
Grammar:
super(Subclass name, self).Method Name()
The subclass name and self are required to be passed in, the method within the parent is called, and the parameters are required by the parent's method.To pass in the subclass name and self, the method within the parent class is called, and parameters are required by the parent class's method.
class A: def __init__(self, name): self.name = name print("Parent class__init__Method executed!") def show(self): print("Parent class show Method executed!") class B(A): def __init__(self, name, age): super(B, self).__init__(name=name) self.age = age def show(self): super(B, self).show() obj = B("jack", 18) obj.show()
polymorphic
First look at the following code:
class Animal: def kind(self): print("i am animal") class Dog(Animal): def kind(self): print("i am a dog") class Cat(Animal): def kind(self): print("i am a cat") class Pig(Animal): def kind(self): print("i am a pig") # This function takes an animal parameter and calls its kind method def show_kind(animal): animal.kind() d = Dog() c = Cat() p = Pig() show_kind(d) show_kind(c) show_kind(p) ------------------ Print results: i am a dog i am a cat i am a pig
Dogs, cats, and pigs inherit animals and each overrides the kind method.*Show_The type() function takes an animal parameter and calls its kind method.It can be seen that whether we pass animal a dog, cat or*pig, we can call the appropriate method correctly and print the corresponding information.This is polymorphism.
In fact, due to Python's dynamic language characteristics, it is passed to the function show_The animal parameter of type () can be any type as long as it has a method of type ().The type is not checked when an instance method is invoked by a dynamic language. As long as the method exists and the parameters are correct, it can be invoked.This is the "duck type" of dynamic language. It does not require a strict inheritance system. An object can be considered a duck as long as it looks like a duck and walks like a duck.
Member protection and access restrictions
Inside the class, there are a variety of variables and methods.These data members can be called outside the class by an instance or class name, for example:
class People: title = "Human beings" def __init__(self, name, age): self.name = name self.age = age def print_age(self): print('%s: %s' % (self.name, self.age)) obj = People("jack", 12) obj.age = 18 obj.print_age() print(People.title)
The above calls are needed in most cases, but often we don't want all variables and methods to be accessed externally. We need to protect certain members and restrict access to them.Such programs are robust, reliable, and business-logical.
In JAVA-like languages, there is a private keyword that makes certain variables and methods private, preventing external access.However, Python does not have this mechanism, and Python uses changes in variable and method names to do this.
Click for a complete set of Python zero Basics
In Python, if you want internal members not to be accessed externally, you can precede their names with two underscores u,This member becomes a private member.Private members can only be accessed inside the class, not outside.
class People: title = "Human beings" def __init__(self, name, age): self.__name = name self.__age = age def print_age(self): print('%s: %s' % (self.__name, self.__age)) obj = People("jack", 18) obj.__name ------------------------------ Traceback (most recent call last): File "F:/Python/pycharm/201705/1.py", line 68, in <module> obj.__name AttributeError: 'People' object has no attribute '__name'
So if you want to uName and uWhat about age access and modification?Create externally accessible get and set methods inside the class!
class People: title = "Human beings" def __init__(self, name, age): self.__name = name self.__age = age def print_age(self): print('%s: %s' % (self.__name, self.__age)) def get_name(self): return self.__name def get_age(self): return self.__age def set_name(self, name): self.__name = name def set_age(self, age): self.__age = age obj = People("jack", 18) obj.get_name() obj.set_name("tom")
Doing so not only protects the data but also provides an interface for external access, but also gets_Name, set_Name These methods can add additional operations to detect, process, process, package, and so on, which is very useful!
Membership and underline summary of classes:
Special Members and Magic Methods
Python There are a lot of similarities __doc__ This special member that starts and ends with a double underscore and "magic method". They have a very important position and role, and they are Python One of the unique grammars of a language!