python-Object-oriented (combination, encapsulation and polymorphism)

Source: Internet
Author: User

First, the combination

What is a combination?

The type of a property of a class is the type of another custom class, or it can be said that an object has one property, and the value of that property is an object of another class.

Reduces code redundancy between classes by indirectly consolidating two classes by adding properties to one object (where the property is an object of another class)

class A:     Pass class B:     Pass  = B () B.A=a ()

Use the previous code to improve:

classOldboypeople:school='Oldboy'    def __init__(self,name,age,sex): Self.name=name Self.age=Age Self.sex=Sexclassoldboystudent (oldboypeople):def __init__(self,name,age,sex,score=0): Oldboypeople.__init__(self,name,age,sex) Self.score=score Self.courses=[]    defChoose (self):Print('%s Choosing Course'%self.name)defTell_all_course (self):Print('students [%s] are enrolled in the following courses:'%self.name) forObjinchSelf.courses:obj.tell_info ()classOldboyteacher (oldboypeople):def __init__(self,name,age,sex,level): Oldboypeople.__init__(self,name,age,sex) Self.level=Level self.courses= []    defscore (self,stu,num): Stu.score=NumdefTell_all_course (self):Print(('the teacher [%s] teaches the following courses'%self.name). Center (50,'*'))         forObjinchSelf.courses:obj.tell_info ()Print('*'*60)classcoures:def __init__(self,c_name,c_price,c_period): Self.c_name=c_name Self.c_perice=C_price Self.c_period=C_perioddefTell_info (self):Print('< course Name:%s Price:%s Period:%s'%(Self.c_name,self.c_perice,self.c_perice)) Stu= Oldboystudent ('ZFJ', 18,'male') teh= Oldboyteacher ('Egon', 19,'Femal', 10)#print (stu.__dict__)Python = coures ('python full stack development','1900','5mons') Linux= Coures ('Linux Architects',' -','3mons') stu.courses.append (python) teh.courses.append (python) stu.tell_all_course () Teh.tell_all_course ()
View CodeSecond, polymorphic

Polymorphism refers to the same species or different forms of things

Polymorphism: In the context of polymorphism, the object can be used directly without considering the specific type of the object

The essence of polymorphism: unification

People, dogs, pigs are all the same animals, they have the characteristics of speaking and running, will be a common feature stripped out to form the parent class

ImportABCclassAnimal (metaclass=ABC. Abcmeta): @abc. AbstractmethoddefSpeak (self):Pass@abc. AbstractmethoddefRun (self):Pass#Animal () # The parent class is only used to build the specification, not to instantiate, and not to implement an internal methodclasspeople (Animal):defSpeak (self):Print('Say hello')    defRun (self):PassclassDog (Animal):defSpeak (self):Print('Wang Woo')    defRun (self):PassclassPig (Animal):defSpeak (self):Print('Hum hum')    defRun (self):Passobj1=people () obj2=Dog () obj3=pig ()

Here comes the abstract class, we import the ABC module,ABC. Abcmeta is a metaclass that is used to create an abstract base class in a Python program.

After the corresponding method is preceded by a row with @abstractmethod, the new line begins to define the appropriate method. The implementation of the method is an abstract method, after the subclass inherits, if need to use this method must use the new method to implement it

The bottom line is that abstract classes cannot be instantiated, and subclasses must implement (abstract) all abstract methods of the parent class

Python advocates Duck type: "When you see a bird walking like a duck, swimming like a duck, and barking like a duck, then this bird can be called a duck." ”

In duck type, the focus is not on the type of the object itself, but how it is used

classDisk:defRead (self):Print('Disk Read')    defWrite (self):Print('Disk Write')classMemory:defRead (self):Print('Mem Read')    defWrite (self):Print('Mem Write')classCpu:defRead (self):Print('Cpu Read')    defWrite (self):Print('Cpu Write') Obj1=Disk () obj2=Memory () obj3=Cpu () obj1.read () Obj2.read () Obj3.read ( )
View CodeThree, Package

To hide the name in the namespace, which is not externally

Storage: Name in Container/namespace

Encapsulation: Privatization of classes ' properties and methods, resulting in invisible externally visible

How to encapsulate?

Preceded by _ (no _ end) for attributes defined within a class

classFoo:#part1    #__num = +    #Part2    #def __init__ (self, name):    #self.__name = name    #Part3    def __test(self):#change to form _foo_test        Print("Test")#part1#foo = foo ()#print (foo.__num)#Part2#foo = foo ("* * * *")#print (foo.__name)Foo=Foo () foo._foo__test ()
View Code

To access a property that is privatized, you need to precede the object you want to access by adding the _ Class name. Method name

Iv. Property

Property decorators are used to disguise function properties within a class as data attributes, with Getter,setter, (deleter) methods

classCar:def __init__(self, Name, type): Self.__name=name self.__type=typedef __str__(self):return ">>"+ Self.__name+"""+ Self.__type+""<<"    #__name is not visible externally, but the outside world needs to access, so through the method of external indirect to provide __name    #The method of accomplishing this kind of function is called interface@property#name () = Name    defname (self):#can do a series of safe operations        returnSelf.__name    #@name. Getter    #def name (self):    #return Self.__name    #@name. Setter    #def set_name (self, name):    #self.__name = name@name. Setterdefname (self, name): Self.__name=Namecar= Car ("BMW","7 Series")#>> BMW "7 Series" <<Print(CAR)#access attributes, with () not enough to force lattice#print (Car.name ())Print(Car.name)#fetch value: Getter#car.set_name ("Audi")#car.set_name = "Audi" # Settings: SetterCar.name ="Audi"Print(CAR)
View Code

We have to keep trying.

python-Object-oriented (combination, encapsulation and polymorphism)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.