Python Basics

Posted by 2gd-2be-2rue on Wed, 23 Feb 2022 19:18:27 +0100

1. Introduction to three major features of object-oriented

Python is an object-oriented language. It also supports three major features of object-oriented programming: inheritance, encapsulation (hiding) and polymorphism.

  • Encapsulation (hidden)
    Hide the properties and implementation details of the object, and only provide necessary methods. It is equivalent to "encapsulating details" and only exposing "relevant calling methods".
  • inherit
    Inheritance can make subclasses have the characteristics of parent classes and improve the reusability of code. When the original parent class design remains unchanged, new functions can be added or existing algorithms can be improved.
  • polymorphic
    Polymorphism means that the same method call will produce different behaviors due to different objects.

2. Succession

Inheritance is not only an important feature of object-oriented programming, but also an important means to realize "code reuse".
The existing class is called "parent class or base class", and the new class is called "child class or derived class".

2.1 syntax format

Python supports multiple inheritance. A subclass can inherit multiple parent classes. The inherited syntax format is as follows:

class Subclass class name(Parent class 1[´╝îParent class 2,...]): 
	Class body

If no parent class is specified in the class definition, the default parent class is the object class. In other words, object is the parent class of all classes, which defines some default implementations common to all classes, such as:__ new__ ().
When you define a subclass, you must call the constructor of the parent class in its constructor. The calling format is as follows:

Parent class name.__init__(self, parameter list)
class Person:
	def __init__(self,name,age):
		self.name = name
		self.__age = age
	def say_age(self):
		print(self.name,"Your age is:",self.__age)
		
class Student(Person):
	def __init__(self,name,age,score):
		self.score = score
		Person.__init__(self,name,age) #The constructor contains the constructor that calls the parent class. As needed, not necessary. Subclasses do not automatically call the parent class__ init__ (), we must explicitly call it.
s1 = Student("Zhang San",15,85)
s1.say_age()
print(dir(s1))

Operation results:

Zhang San's age is 15
['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'say_age', 'score']

2.2 inheritance and rewriting of class members

  1. Member inheritance: the subclass inherits all members of the parent class except the constructor.
  2. Method override: subclasses can redefine the methods in the parent class, which will override the methods of the parent class, also known as "override"

[operation] cases of inheritance and rewriting

class Person:
	def __init__(self,name,age):
		self.name = name
		self.age = age
	def say_age(self):
		print(self.name,"Your age is:",self.age)
	def say_name(self):
		print("I am",self.name)
class Student(Person):
	def __init__(self,name,age,score):
		self.score = score
		Person.__init__(self,name,age) #The constructor contains the constructor that calls the parent class
	def say_score(self):
		print(self.name,"Your score is:",self.score)
	def say_name(self): #Override the method of the parent class
		print("Report to the teacher, I am",self.name)
s1 = Student("Zhang San",15,85)
s1.say_score()
s1.say_name()
s1.say_age()

Operation results:

Zhang San's score is 85
 Report to the teacher, I'm Zhang San
 Zhang San's age is 15

2.3 viewing the inheritance hierarchy of classes

Through class method mro() or class attribute__ mro__ You can output the inheritance hierarchy of this class.
[operation] view the inheritance hierarchy of the class

class A:pass
class B(A):pass
class C(B):pass
print(C.mro())

Execution result:

[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]

2.4 object root class

Object class is the parent class of all classes, so all classes have the properties and methods of object class

2.5 dir() view object properties

In order to learn more about objects, we first learn the built-in function dir(), which allows us to easily see all the properties of the specified object.
[test] view all attributes of the object and compare with the object

class Person:
	def __init__(self,name,age):
		self.name = name
		self.age = age
	def say_age(self):
		print(self.name,"Your age is:",self.age)
obj = object()
print(dir(obj))
s2 = Person("Gao Qi",18)
print(dir(s2))

Operation results:

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say_age']

From the above, we can find the following points:

  • The Person object adds six attributes:
    (1)__ dict __ (2)__ module __ (3)__ weakref __ (4)age (5)name (6)say_age
  • As a subclass of object, the Person class obviously contains all the attributes of object.
  • We print age, name, say_age, find say_ Although age is a method, it is actually an attribute. However, the type of this attribute is "method".
age <class 'int'>
name <class 'str'>
say_age <class 'method'>

2.6 rewriting__ str__ () method

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__ str__ () can be overridden.

class Person:
	def __init__(self,name,age):
		self.name = name
		self.__age = age
	def __str__(self): '''Converts an object into a string, typically used for print method''' 
		return "The name is:{0},Age is{1}".format(self.name,self.__age)
p = Person("Gao Qi",18)
print(p)

Operation results:

Name: Gao Qi,The age is 18

2.7 multiple inheritance

Python supports multiple inheritance. A subclass can have multiple "direct parent classes". In this way, it has the characteristics of "multiple parent classes". However, because this will be extremely complicated by the "overall level of class", try to avoid using it.

#multiple inheritance
class A:
def aa(self):
print("aa")
class B:
def bb(self):
print("bb")
class C(B,A):
def cc(self):
print("cc")
c = C()
c.cc()
c.bb()
c.aa()

Operation results:

cc
bb
aa

2.8 MRO()

Python supports multiple inheritance. If there are methods with the same name in the parent class, the interpreter will search in order "from left to right" when the child class does not specify the parent class name.
MRO (Method Resolution Order): Method Resolution Order. We can obtain the "class hierarchy" through the mro() method, and the method parsing order is also found according to the "class hierarchy".

#multiple inheritance
class A:
	def aa(self):
		print("aa")
	def say(self):
		print("say AAA!")
class B:
	def bb(self):
		print("bb")
	def say(self):
		print("say BBB!")
class C(B,A):
	def cc(self):
		print("cc")
c = C()
print(C.mro()) #Print class hierarchy
c.say() #The search method of the interpreter is "from left to right". At this time, say() in class B will be executed

2.9 super() get the parent class definition

In the subclass, if we want to get the method of the parent class, we can do it through super().
super() represents the definition of the parent class, not the parent object.

#super()
class A:
	def say(self):
		print("A: ",self)
		print("say AAA")
class B(A):
	def say(self):
		#A.say(self) calls the say method of the parent class
		super().say() #Call the method of the parent class through super()
		print("say BBB")
b = B()
b.say()

Operation results:

A: <__main__.B object at 0x007A5690>
say AAA
say BBB

3. Polymorphism

polymorphism refers to that the same method call may produce different behaviors due to different objects.
Note the following two points about polymorphism:

  • Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes.
  • There are two necessary conditions for polymorphism: Inheritance and method rewriting.
#polymorphic
class Animal:
	def shout(self):
		print("The animal gave a cry")
class Dog(Animal):
	def shout(self):
		print("Puppy, woof, woof")
class Cat(Animal):
	def shout(self):
		print("Kitten, meow, meow")
def animalShout(a):
	if isinstance(a,Animal):
		a.shout() #The actual behavior of the shot method is different depending on the incoming object.
animalShout(Dog())
animalShout(Cat())

Operation results:

Puppy, woof, woof
 Kitten, meow, meow

Topics: Python