Object-oriented three major features
First, the package
#1. Encapsulate the content somewhere
#Create ClassclassFoo:def __init__(self,name,age):#called a construction method that automatically executes when an object is created according to a classSelf.name=name Self.age= Age#to create an object from class Foo#automatic execution of the __init__ method of the Foo classObj1=foo ("Wupeiqi", 18)#encapsulate Wupeiqi and 18 separately into the properties of the name and age of Obj1 (that is, self)Obj2=foo ('Alex', 73)
#2. Calling the encapsulated content from somewhere
#2.1 calling encapsulated content directly from an object
classFoo ():def __init__(self,name,age):#called a construction method that automatically executes when an object is created according to a classSelf.name=name Self.age=ageobj1= Foo ('Wupeiqi', 18)Print(Obj1.name)Print(obj1.age) obj2=foo ('Alex', 73)Print(Obj2.name)Print(Obj2.age)
#2.2 indirect invocation via self
classFoo ():def __init__(self,name,age):#called a construction method that automatically executes when an object is created according to a classSelf.name=name Self.age= Agedefdetail (self):Print(Self.name)Print(self.age) obj1=foo ('Wupeiqi', 18) Obj1.detail ()#python defaults to obj1 to the self parameter, which is Obj1.detail (OBJ1), so the self=obj1 inside the method, namely: Self.name is Wupeiqi;self.age isObj2=foo ('Alex', 73) Obj2.detail ()
Ii. inheritance
#继承
# Animals: Eat, drink, pull, sprinkle
#
# Cat: Meow Meow (cat inherits function of animal)
#
# Dog: Barking (dogs inherit the function of animals)
classAnimal:defEat (self):Print('%s Eat'%self.name)defDrink (self):Print('%s Drink'%self.name)defshit (self):Print('%s Pull'%self.name)defpee (self):Print('%s Caesar'%self.name)classCat (Animal):def __init__(self,name): Self.name=name Self.breed='Cat' defCry (self):Print('Meow Meow')classDog (Animal):def __init__(self,name): Self,name=name Self.dreed='Dog' defCry (self):Print('Barking')############ #执行 ##############C1=cat ('Small White House of Little black Cat') c1.eat () C2=cat ('Little Black family's little white cat') C2.drink () D1=dog ('Fat family's little thin dog') d1.eat ()
Three, polymorphic
Python Object-oriented