程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python basics -day10 (object oriented)

編輯:Python

1、 The concept of object orientation

The process of categorizing a class that has common attributes is called object-oriented .

2、 matters needing attention

class When defining a class , The first letter of a class name must be capitalized

3、 Object oriented case

 1 class Person(object):
 2 def __init__(self,name,age): #name,age It can be understood as the attribute of a class ;init For initialization ; The functions defined in a class are called constructors / Constructors 
 3 self.name=name # Instance attributes 
 4 self.age=age
 5 print("start")
 6 def __del__(self): # Cleanup operations 
 7 print("end")
 8 def show(self): #self For the class itself , Do not omit 
 9 print("name:{0},age:{1}".format(self.name,self.age))
10 obj=Person(name="wuya",age=18) # To call a variable in a class 、 Methods, functions, etc , First, you need to instantiate the class ;obj It's a class Person() Instantiated object , The process of class instantiation is also the process of class initialization . The instantiation process of a class is also the process of initializing a constructor ( It's called __init__ Methods )
11 obj.show()
12 #Person(name="wuya",age=18).show() # Call method with class name 

The result of running the above code is :

4、 The execution order of the methods in the class : Initialization method -> Specific method -> Cleaning method

5、 Object oriented features

1) encapsulation

a. Instance attributes

b. Data attribute ( Variables in class )

2) Inherit

3) polymorphic

6、 Method :

a. Common method : Belong to the object , Also belong to class , Can only read and write ;

b. Characteristic method : Belong to the object , Only the read attribute is available , Methods cannot have formal arguments ;

c. Static methods : Belong to category , Can only be called with class name , Generally, data attributes are handled by static methods

7、 Encapsulate the starter instance

 1 class Animal(object):
 2 def __init__(self,age):
 3 self.age=age
 4 def getAge(self):
 5 return self.age
 6 def setAge(self,age):
 7 if age>10 and age<100:
 8 self.age=age # It is allowed to modify the age 
 9 else:
10 print(" Age error ")
11 objAnimal=Animal(age=25) # Class instantiation 
12 print(objAnimal.getAge()) # Output the call result of the method to get the age 
13 objAnimal.setAge(age=11) # Call the method to modify the age 
14 print(objAnimal.getAge()) # Output the call result of the method to get the age 

8、 Advanced instances of encapsulation

 1 class Animal(object):
 2 address=" The earth " # Data attribute 
 3 def __init__(self,age):
 4 self.age=age # Instance attributes 
 5 # @staticmethod
 6 def address(self): # Static methods , Data attributes are handled using static methods 
 7 return " The earth "
 8 def show(self,name="*"): # Common method , read-write 
 9 print("it come from {0},and it's age is {1},and it's name is {2}".format(self.address(),self.age,name))
10 def func(self,**kwargs):
11 print(kwargs)
12  @property
13 def info(self): # Characteristic method , read-only ( Only output )
14 print("hello world")
15  @property
16 def getAge(self): # Characteristic method , read-only ( Only return to )
17 return self.age
18 objAnimal=Animal(age=30) # Class instantiation 
19 objAnimal.show() # Calling normal methods 
20 #objAnimal.show(name="monkey")
21 # Animal().show(name="monkey")
22 # Animal(age=10).address()
23 objAnimal.func(name="cch",age=18,city=" Xi'an ")
24 objAnimal.info # Feature method calls 
25 print(Animal.address(""))
26 print(objAnimal.age)

 

 

 

 9、 Inherit

1) Concept

Parent class ( Base class ): Inherited class

Subclass ( Derived class ): Inherit other classes

2)Java and Python The difference between inheritance

Java It's a single inheritance ,Python It's multi inherited

3) Inherit from the parent class of :

a、 Variable ( Data attribute )

b、 Instance attributes

c、 Method

3) Method rewriting

When the methods of the parent class cannot meet the needs of the child class , The subclass overrides the methods of the parent class , Then the object after subclass instantiation calls this method , Priority is given to subclass methods .

 1 class Father(object):
 2 address=" Xi'an "
 3 def __init__(self,name,age):
 4 self.name=name
 5 self.age=age
 6 def info(self):
 7 print("this is a father's method")
 8 class Son(Father):
 9 def __init__(self,name,age,score):
10 Father.__init__(self,name,age) # The subclass inherits the instance property of the parent class 
11 self.score=score
12 def show(self):
13 print("name is {0},and age is {1},and score is {1}".format(self.name,self.age,self.score))
14 def info(self): # The method of the parent class overrides 
15 print("this is a son's method")
16 son=Son(name="wuya",age=18,score=99)
17 son.show()
18 print(son.address) # The subclass inherits the variables of the parent class ( Data attribute )
19 son.info() # no need print,info() There is print, Function and return value , The output function is null . Subclasses override methods of the parent class , Then the object after subclass instantiation calls this method , Priority is given to subclass methods .

The result of running the above code is :

 

 

 10、 Inheritance order

1) From top to bottom ( Prerequisite ):

a. Single inheritance

b. The subclass overrides the method of the parent class

2) From left to right ( Prerequisite ): Subclasses inherit from multiple classes ( Subclasses can inherit multiple parent classes , But the parent classes must be siblings .)

3) So in Python in , be based on MRO The parsing order rule of , You'll start looking for the base class from left to right , If you find the second one ⼀ Matching attribute classes , It will stop ⽌ lookup , without , Then keep looking , Until you find a match

To the end .MRO It's really just through ⼀ individual C3 Linear algorithm to achieve , Its core idea is :

Subclasses will be superior to parent class checking

Multiple parent classes are checked in turn according to their order in the list

If there are two legitimate choices for the next class , Only the first... Can be selected ( Linear search )

11、 Examples of inheritance order

 1 class Father(object):
 2 def __init__(self,name,age):
 3 self.name=name
 4 self.age=age
 5 def funM(self):
 6 print("father")
 7
 8 class Mother(object):
 9 def funM(self):
10 print("mother")
11
12 class Son(Father,Mother): # Subclass Son Inherited two parent classes
13 def __init__(self,name,age,score):
14 Father.__init__(self,name,age) # Subclass Son Inherited the parent class Father and Mother Instance properties for 
15 self.score=score
16
17 son=Son(name="ccj",age=18,score=100)
18 son.funM()
19 print(Son.mro()) # Call... With a class name mro, View the execution order of the class 

The execution result of the above code is :

 

 

 12、 Subclass inherits multiple non sibling parent class error examples

 1 class Person(object):
 2 pass
 3
 4 class Father(Person):
 5 def __init__(self):
 6 pass
 7 def funM(self):
 8 print("father")
 9 class Mother(object):
10 def funM(self):
11 print("mother")
12
13 class Son(Person,Father): # The child class inherits multiple parent classes that are not of the same level , The code will report an error ,z Subclasses can inherit multiple parent classes , But the parent classes must be siblings .
14 def __init__(self,score): 15 Father.__init__(self) 16 self.score=score 17 son=Son(score=90) 18 son.funM() 19 print(Son.mro())

The running result of the above code is ;

 

 

 13、 Examples of inherited method call errors

 1 class Person(object):
 2 pass
 3
 4 class Father(Person):
 5 def __init__(self):
 6 pass
 7
 8 class Mother(Person):
 9 def funM(self):
10 print("mother")
11
12 class Son(Father): # There is no... In the parent class inherited by the subclass funM Method , The code will report an error 
13 def __init__(self,score):
14 Father.__init__(self)
15 self.score=score
16
17 son=Son(score=99)
18 son.funM()

The running result of the above code is :

 

 14、 Example of inherited method call error correction

 1 class Person(object):
 2 def funM(self):
 3 print("person")
 4
 5 class Father(Person):
 6 def __init__(self):
 7 pass
 8
 9 class Mother(Person):
10 def funM(self):
11 print("mother")
12
13 class Son(Father): # The parent class of the subclass inheritance method is Father
14 def __init__(self,score):
15 Father.__init__(self)
16 self.score=score
17
18 son=Son(score=99)
19 son.funM() # Subclasses call methods , First, look up... From the subclass , Then find the inherited parent class , If you don't find , Then find the parent class of the parent class .
20 print(Son.mro())

The result of the above method is :

 

 15、 The question of inheritance history

python2 It's depth first ,python3 It's breadth first

 1 class A:
 2 def show(self):
 3 print('A')
 4
 5 class B(A):
 6 pass
 7
 8 class C(A):
 9 def show(self):
10 print('C')
11
12 class D(B,C):
13 pass
14
15 if __name__ == '__main__':
16 obj=D()
17 obj.show() #python2 The result of the execution is A,pyhton3 The result of running in is C

16、 polymorphic

Many advantages can be summarized as follows , Specific for :

Increased continuous flexibility

Added continuous additional extensions

 1 class Animal(object):
 2 def talk(self):
 3 print(" Animals can call ")
 4
 5 class Dog(object):
 6 def talk(self):
 7 print(" A dog barks ")
 8
 9 class Cat(object):
10 def talk(self):
11 print(" Cats bark, too ")
12
13 def func(animal):
14  animal.talk()
15 if __name__ == '__main__':
16 dog=Dog()
17 func(animal=dog)

The running result of the above code is :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved