Object-oriented Python

Source: Internet
Author: User

First we should know that Python is already an object-oriented language at the beginning of design, so it is easy to say that Python creates a class and object.

An introduction to object-oriented technology
    • class: Used to describe a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection, which is an instance of the class.
    • Class variables : Class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are usually not used as instance variables.
    • data members : Class variables or instance variables are used to manipulate data about classes and instance objects.
    • method Overrides : If the method inherited from the parent class does not meet the requirements of the subclass, it can be overridden, and the procedure is called overwriting, also called the override of the method.
    • instance variable : A variable defined in a method that is used only for classes in the current instance.
    • inheritance : A derived class (derived class) that inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object.
    • instantiation : Creates an instance of a class, the concrete object of the class.
    • method : A function defined in a class.
    • Object : an instance of the data structure defined in the class. The object consists of two data members (class variables and instance variables) and methods.
Create Class

Create a class, which is a keyword, just like the def in a function. Basic formats such as

Class ClassName:    def function name (self):        passobj = ClassName () obj. function name () #执行

In the creation class, the self behind the function is a required parameter, equivalent to the passed object, and obj represents an object at this time. For example, a simple instance

Class Foo:    def f (self, args):        return ARGSS = foo () ret = S.F ("You're Handsome") print (ret)
Three main object-oriented features: encapsulation, inheritance, polymorphic encapsulation

is to encapsulate the content somewhere and call it later. First look at an example

Class Foo:    def f (self,args):        print (Self.name, self.age, self.gender,args) z = foo () z.name = "flash" z.age = 18z.gender = "Man" Z.f ("You Are Handsome") #这种也能实现封装的功能, but will pass many parameters, appear relatively low

In fact, there is a special method in the class: The construction method, which allows us to implement the encapsulation will be more convenient and beautiful. Such as

Class Person:    def __init__ (self, Name, age):        SELF.N = name        SELF.A = Age    def foo (self):        print (SELF.N , self.a) Flash = person ("Flash", "Flash.foo") #注: The __init__ is a construction method, which executes automatically when the class is created.
Inherited

Similar to the inheritance in reality, the subclass inherits the parent class. Inheritance is all inherited by default, but you can inherit only the benefits. First look at an example of all inheritance.

classFather:defEat (self):Print("Eat")    defDrink (self):Print("Drink")classSon (Father):defsink (self):Print("La") obj=Son () Obj.sink () obj.eat () Obj.drink ()
Inherit all

Sometimes we don't want to inherit it all, that's all we need to change.

classFather:defEat (self):Print("Eat")    defDrink (self):Print("Drink")classSon (Father):defDrink (self):Print("La") Super (Son, self). Drink ()#methods for executing drink in a parent classobj =Son () obj.drink ()
Partial Inheritance

So the question is, if a subclass has two parent classes, and each parent class has its own parent class, what if the parent class has the same parent class?

In Python, the principle that the parent class is last executed is followed by the first left, right, and one path to black, with the same parent class.

For example, the following example

classBase:PassclassF2 (Base):defA (self):Print("f2.a") self.b ()defB (self):Print("f2.b")classF3 (F2):defB (self):Print("f3.b")classSon (F3,F2):Passobj=Son () obj.a ()
Multiple InheritancePolymorphism Polymorphism (POLYMORPHISN) is a technique that allows you to set a parent object to be equal to one or more of his child objects, and after assignment, the parent can operate differently depending on the attributes of the child object that is currently assigned to it. To put it simply, it is a sentence: A pointer to the parent class type is allowed to be assigned a pointer to the child class type. So what is the role of polymorphism? We know that encapsulation can hide implementation details and make code modular; Inheritance can extend existing code modules (classes); they are all designed to-code reuse. And polymorphism is for another purpose--interface reuse! The role of polymorphism is to ensure that classes are called correctly when inheriting and deriving a property of an instance of any class in the family tree. Fields and methods for class members

Application Scenarios

If you need to save some values in an object and perform a function, you need to use the values in the object-> the normal method
No value in any object is required, static method

Field
    • Normal field: The object is persisted, and execution can only be accessed through the object.
    • Static fields: persisted in the class, execution can be accessed through the object or through the class.
Method
    • Common method, saved in a class, called by an object, self= "Object
    • Static methods, which are saved in the class, are called directly by the class
    • Class method, saved in the class, called directly by the class, cls= "current class
Property

By way of definition, by the mode of the field to call

For example

class provice:     " China " # static fields belong to class    def __init__ (self,n):         # normal field belongs to object Henan        Print  = Provice (" Henan ")print(provice.country) Henan.name
Field
classFoo:defF1 (self):#Common Methods        Print(123) @staticmethod#Static Methods    defSTA ():Print() @classmethod#class Method    defCLASSMD (CLS):Print("A, b") @property#Properties    defper (self):Print("AAA") obj=Foo () obj.f1 () Foo.sta ( )#call a static method without creating an objectFOO.CLASSMD ()#Calling class methodsobj1= Foo ()#Call PropertiesObj1.per
Method

For example, the problem of paging with common property attributes

classparagnation:def __init__(self,page):Try: P=int (page)exceptException as E:p= 1Self.page=P @propertydefStart (self): P= (self.page-1) * 10returnP @propertydefEnd (self): P= Self.page * 10returnPLI= [] forIinchRange (1000): Li.append (i) whiletrue:p= Input ("Please enter the page number:") obj=paragnation (P)Print(Li[obj.start:obj.end])
PropertyMember modifiers
    • Total members
    • Private methods

Where private members are represented by double underscore + field name (__ field name)

Private members cannot be accessed externally, and external access can only be accessed indirectly through methods inside the class. For example

classF:def __init__(self): self.__age= 18defShow (self):returnSelf.__ageclassS (F):def __init__(self, Name, gender): Self.name=name Self.gender=Gender super (S, self).__init__()    defShow (self):Print(Self.name)#print (self.__age) #子类不能继承到父类的私有变量, otherwise it will error, if you want to inherit can be indirectly accessed through the common method of the parent class        Print(self.gender) P= S ("Flash","male") P.show () R=p.show ()Print(r)
Private Methods

Note: Subclasses cannot inherit private methods of the parent class, that is, the private method of the parent class cannot be accessed directly in the subclass, but only indirectly through the method of the parent class.

Special members that are common in Python

__init__     Class () automatically executes the    __del__     del Object [222]    __call__     object ()  class () () automatically executes    __int__      int (object)     __str__      str ()        __add__     #对象的封装的加法    __dict__     # All content encapsulated in the object is returned in the form of a dictionary    __getitem__  # Slice (slice type) or index    __setitem__    __delitem__        __iter__                # If there is a __iter__ method in the class, Object = "can iterate over the object                # The return value of the object. __iter__ (): Iterator                # for Loop, iterator, next # for                loop, iteration object, object. __iter__ (), iterator, next                # 1, __iter in Class F class that performs the Li object __ method and get its return value                # 2, loop the object returned in the previous step    
Exception handling

Common Terminology Database Processing

Main syntax blocks

Try:    custom content except Exception as E:    print ("message")

Several common patterns are listed below

try:i = Int (input (input >>>>)) except Indexerror as E:print ("Index Error ", E) except ValueError as E:print (" ValueError ", E) except Exception as E:print (" Exception ", E) else:print (i) F Inally:print ("Success") 
 class   Foo (Exception):  def  __init__   (SELF,MSG): Self.message /span>= msg  __str__   return   Self.message  try  :  raise  Foo ( i ' m error   " "  except   print  (E) 
Custom ModulesReflection
classFoo:def __init__(self, Name, age): Self.name=name Self.age= AgedefShow (self):Print("%s-%s"%(Self.name, self.age)) obj= Foo ("Flash", 18)#print (obj.name)func= GetAttr (obj,"name")Print(func) func1= GetAttr (obj,"Show")Print(Func1 ())Print(Hasattr (obj,"name")) setattr (obj,"Gender","Mans")Print(Obj.gender) delattr (obj,"name") Obj.name
ExampleSingle-Case mode
classfoo:v=None @classmethoddeffunc (CLS):ifCLS. V:returnCLS. VElse: CLS. V=Foo ()returnCLS. Vobj=Foo.func ()Print(obj. V)Print(obj) obj1=Foo.func ()Print(OBJ1)
Example

  

Object-oriented Python

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.