Creating a Self object is a very central concept of python, in fact, Python is called an object-oriented language, and this chapter describes how to create objects. and object-oriented concepts: inheritance, encapsulation, polymorphism.Polymorphic: You can use the same action for objects of different classes.Encapsulation: The work details of hidden objects in the external world.Inheritance: A specialized c
#one interface, multiple implementations#implementing the reuse of interfacesclassAnimal:def __init__(self, name):#Constructor of the classSelf.name =namedefTalk (self):#Abstract method, defined by convention only Pass #Raise Notimplementederror ("subclass must implement abstract method")#This is the realization of polymorphism.@staticmethoddefAnimal_talk (obj): Obj.talk ()classCat (Animal):defTalk (self):Print('meow!')classDog (Animal):defTalk
biggest benefit is that the subclass obtains the full functionality of the parent class. The Print_heorshe method of the parent class can be used directly as follows student classWhen instantiating student, subclasses need to provide the two attribute variables required by the parent class name and sex1 classPerson :2 def __init__(self,name,sex):3Self.name =name4Self.sex =Sex5 6 defPrint_heorshe (self):7 ifSelf.sex = ="male":8 Print("He")9 elifSelf.se
,age)# Note To display the call to the parent class constructor method, and pass the argument selfSelf.sno =Sno # Student class has sno,mark two properties Self.mark=MarkdefGetsno (self):returnSelf.snodefGetmark (self):returnSelf.markclassTeacher (Universitymember): # defines a subclass Teacher def __init__(self,name,age,tno,salary): Universitymember.__init__(self,name,age) Self.tno=TNO # Teacher class has tno,salary two properties self.salary=SalarydefGettno (self):returnSelf.tnodefgets
S12-20160227-day07Pytho Automation Development day07date:2016.02.27 @南非波波Course Outline:Day06Http://www.cnblogs.com/alex3714/articles/5188179.htmlDay07Http://www.cnblogs.com/alex3714/articles/5213184.htmlI. Polymorphism and inheritance of classesPolymorphism of the class: Unified interface Invocation#!/usr/bin/env python# -*- coding:utf-8 -*-class Animal: def __init__(self, name): # Constructor of
()Print(A.mro ())#New class: View inheritance Order#class A (object):p the #新式类#py3--Breadth First#py2--New Class#interview--can correspond to the new class is breadth first Classic class is depth firstPolymorphic#Python does not support polymorphicclassAnimal:PassclassPerson (Animal):defAttack (self):PassclassDog (Animal):defAttack (self):PassdefAttack (obj):# polymorphicObj.attack () d=Dog () p=Person () attack (d)#D.attack ()Attack (P)#P.attack ()
Data encapsulation, inheritance and polymorphism are the three main characteristics of object-oriented.Data encapsulation:In a class, such as the student class (initialization and name and score two properties), each instance has its own name,score of the data. We can access this data through functions, such as printing a student's score. Directly define an output function, output name and corresponding score.However, since the student instance itself
=Abcmeta): @abstractmethoddefFly (self):PassclassWalk_animal (metaclass=Abcmeta): @abstractmethoddefWalk (self):PassclassSwim_animal (metaclass=Abcmeta): @abstractmethoddefSwim (self):PassclassBird (Fly_animal,walk_animal):PassclassDog (Walk_animal,swim_animal):PassclassDuck (Walk_animal,swim_animal,fly_animal):Passb= Bird ()#error Typeerror:can ' t instantiate abstract class Bird with abstract methods fly, walk#the class that inherits the canonical interface class must implement the method of a
->d->b->e->c->a# Classic class Inheritance Order: Unity in F->d->b->a->e->c#python3 is a new class # Want $ new class and classic class in Pyhon2Polymorphic what is polymorphic: Same method invocation, performing different actionsSend the same message to different objects (!!!) Obj.func (): Is the method func that called obj, also known as a message Func sent to obj, and different objects have different behavior (that is, methods) when they are received. In other words, each object can respond t
First, the main content:Interface class: ( Only in the work, writing a specification.)Abstract class:Usefulness: At work, if you prescribe several classes, you must have the same method, if you are abstract class.Packaging:1, put some properties or methods (some useful information) in a space.2, Private member encapsulation: private static variable, private property, Private method feature: +__ double underline before variable, and outside class, subclass accesses private variable, private metho
Polymorphism)
Literally, the behavior of the same method varies with the context.
Wikipedia: Polymorphism (computer science), The ability incomputer programming to present the same interface for differing underlyingforms (data types ).
1,Function Polymorphism(Function polymorphism): that is, function overload)
650) Th
Python is an object-oriented programming language, and an object-oriented basic unit is a classDeclaration of the class:class class_name (): 2 PassThe test is as follows:class C (): ...:pass ...: in [2]: a=C () in [3]: aout[3]: __main__. C instance at 0x07500a30>Inheritance of the class:1In [4]:classBase ():2...:deff (self):3...:Print 'Base'4 ...: 5 6In [5]:classSub (base):7...:Pass8 ...: 9 TenIn [6]: x=Sub () One Ain [7]: x.f
superclass with "," delimited(1) using Super-classClass Filter:def init (self):self.blocked = []def filter (self, sequence):return [x for x in sequence if x not in self.blocked]Class Spamfilter (Filter):def init (self):self.blocked = [' SPAM '](2) See if a class is a subclass of another class, using Issubclass>>> Issubclass (Spamfilter, Filter)Ture>>> Issubclass (Filter, Spamfilter)False(3) If you want to know the base class of a Class (you), you can use its special properties __bases__>>> clas
):#Inherit Studen - def __init__(Self,name,age,clas,score):#Refactoring Construction Method the #studen.__init__ (Self,name,age,clas) #先继承, re-construct -Super (Clas_one,self).__init__(Name,age,clas)#New Class -Self.score=score#adding new Object Members - defTalk (self):#overriding Method + Print('is new talk,%s'%self.name) - defScore_info (self):#new method of adding subclasses + Print(Self.score,'points') A atP=clas_one ('students a', 36,'Three shifts a yea
Because of the polymorphic examples previously written, there seems to be a bit of a problem, now rewrite the makeover.The "" "polymorphic feature is that invoking different subclasses will produce different behaviors without having to know exactly what the subclass actually is," "Classaudiofile:def__init__ ( Self,filename): ifnotfilename.endswith ( Self.ext): #检测来自子类的ext变量是否以按指定的格式结尾, throws an exception if it is not (initialize the audio file in the specified format) raiseexception ("Invalidf
The "" "polymorphic feature is that invoking different subclasses will produce different behaviors without having to know exactly what the subclass actually is," "Classaudiofile:def__init__ ( Self,filename): ifnotfilename.endswith ( Self.ext): #检测来自子类的ext变量是否以按指定的格式结尾, if not, throws an exception raiseexception ("Invalidfileformat") self.filename=filenameclassmp3file (AudioFile):ext= "MP3" defplay (self): print ("Play %smusic ... "%self.filename) Classwavfile (AudioFile): ext = "WAV" defplay (
The classification of polymorphism is widely understood on the Internet, but most of them seem to be based on the classification and understanding of polymorphism in on understanding types, data discovery action, and polymorphism, this article is my personal understanding based on this concept.
There are two types of polymor
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.