Python faces object programming

Source: Internet
Author: User

Object-Oriented Programming:

    • Process oriented: Write base code from top to bottom according to business logic
    • Function: A function code is encapsulated in a function, it will not need to be repeated later, only the function can be called
    • Object-oriented: classify and encapsulate functions to make development "faster, better and stronger ..."

Process-oriented programming is most easily accepted by beginners, it often uses a long code to achieve the specified function, the most common operation in the development process is to paste the copy, that is: Copy the previously implemented code block to the current function.

Packaging

The package is best understood. Encapsulation is one of the object-oriented features and is the main feature of object and class concepts.

Encapsulation, which is the encapsulation of objective things into abstract classes, and classes can put their own data and methods only trusted class or object operation, to the untrusted information hiding.

Inherited

One of the main functions of object-oriented programming (OOP) language is "inheritance". Inheritance refers to the ability to use all the functionality of an existing class and to extend these capabilities without rewriting the original class.

New classes created through inheritance are called "subclasses" or "derived classes."

The inherited class is called the base class, the parent class, or the superclass.

The process of inheritance is from the general to the special process.

To implement inheritance, it can be implemented through inheritance (inheritance) and combination (composition).

In some OOP languages, a subclass can inherit multiple base classes. However, in general, a subclass can have only one base class, and to implement multiple inheritance, it can be implemented by multilevel inheritance.

There are 2 main implementations of the concept of inheritance: implementation inheritance, interface inheritance.

?         Implementation inheritance refers to the ability to use the properties and methods of a base class without additional coding; Interface inheritance is the ability to use only the names of properties and methods, but the subclass must provide the implementation (subclass refactoring method), and one thing to consider when using inheritance is that the relationship between the two classes should be a "belongs" relationship. For example, the Employee is a person and the Manager is a person, so these two classes can inherit the People class. But the Leg class cannot inherit the person class, because the leg is not a human. Abstract classes define only the generic properties and methods that will be created by the subclass.

OO development paradigm is roughly: dividing objects → abstract classes → organizing classes into hierarchical structures (inheritance and compositing) → Designing and implementing several stages with classes and instances.

polymorphicPolymorphism (POLYMORPHISN) is a technique that allows you to set a parent object to be equal to one or more of his child objects, after which the parent object can operate differently depending on the attributes of the child object 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. Pyhon Many grammars support polymorphism, such as Len (), sorted (), you send Len a string to return the length of the string, and the list returns the length of the list. Object-oriented advanced Syntax section Classic class vs New Class

Execute the code below with Python2 and Python3.

#_*_coding:utf-8_*_classA:def __init__(self): SELF.N='A'classB (A):#def __init__ (self):    #SELF.N = ' B '    PassclassC (A):def __init__(self): SELF.N='C'classD (b,c):#def __init__ (self):    #SELF.N = ' D '    Passobj=D ()Print(OBJ.N)

Classical vs New Style:

    • Classic class: Depth first
    • New class: Breadth First
    • Super () Usage
Static Methods

The method of decorating is changed into a static method by @staticmethod Adorner, what is static method? In fact, it is not difficult to understand, the ordinary method can be called directly after instantiation, And in the method can pass self. Invokes an instance variable or a class variable, but a static method cannot access an instance variable or a class variable, and a method that cannot access an instance variable or a class variable is, in fact, nothing to do with the class itself, and its only association with a class is the need to call this method through the class name

class people (object):     def __init__ (self,name):         = name    @staticmethod    def  Eat (self):        print(" %s is eating .... "%= people ("xiao") a.eat ()

The above call will have the following error, saying that eat needs a self parameter, but the call is not passed, yes, when the eat becomes a static method, and then through the instance call will not automatically pass the instance itself as a parameter passed to the auto.

There are two ways to make the above code work correctly

1. When invoked, the instance itself is passed to the Eat method, i.e. d.eat (a)

2. Remove the self parameter in the Eat method, but this also means that you cannot pass self in eat. Calls to other variables in the instance

class people (object):     def __init__ (self,name):         = name    @staticmethod    def  Eat ():        print(" is Eating .... "  = People ("xiao") a.eat ()

Class method 

Class methods are implemented through the @classmethod adorner, the difference between a class method and a common method is that class methods can only access class variables and cannot access instance variables

class people (object):     def __init__ (self,name):         = name    @classmethod    def  Eat (self):        print(" %s is eating .... "%= people ("xiao") a.eat ()

Execute an error saying that dog does not have a name attribute because name is an instance variable and the class method cannot access the instance variable

At this point you can define a class variable, also called name, to see the execution effect

class people (object):     " class Variables "    def __init__ (self,name):         = name    @classmethod    def  Eat (self):        print(" %s is eating .... "%= people ("xiao") a.eat ()
Property method

The function of a property method is to turn a method into a static property by @property

 class   People (object): Name  =  "   " Span style= "COLOR: #0000ff" >def  __init__   ( Self,name): self.name  = name @property  def   Eat (self):  print  ( " %s is eating ....   "%self.name) a  = people ("  xiao   " ) a.eat ()  

Call will be an error, said Nonetype is not callable, because Eat now has become a static property, not a method, want to call already do not need to add () number, direct d.eat can be

The normal call is as follows

A = People ("xiao") a.eat
The special member method of Class 1. __DOC__ represents the description of a class
classFoo (object):"""Description Information"""    def __init__(self): Self.name='Alex'    deffunc (self):Print("is OK")        #return ' func 'obj=Foo ()Print(obj.__doc__)
Output:
Description information

2. __module__ and __class__

__MODULE__ represents the object of the current operation in that module

__CLASS__ represents the class of the object that is currently being manipulated

class C (object):     def __init__ (self):         " name "
 from Import  = C ()print(obj.__module__)print(obj.__ Class__)
Output:
Lib.abc
<class ' LIB.ABC.C ' >

3. __init__ constructs a method that automatically triggers execution when an object is created through a class.

4. __del__

destructor, which automatically triggers execution when the object is freed in memory.

Note: This method is generally not defined because Python is a high-level language, and programmers do not need to be concerned with allocating and releasing memory because this work is done by the Python interpreter, so the destructor calls are automatically triggered by the interpreter when it is garbage collected.

5. The __call__ object is appended with parentheses to trigger execution.

Note: The execution of the construction method is triggered by the creation object, that is: Object = class name (), and the execution of the __call__ method is triggered by parentheses after the object, i.e.: Object () or Class () ()

class A (object):     def __init__ (self):         Pass    def __call__ (Self, *args, * *Kwargs)        : Print  = A () obj (1) output:1
6. __dict__ View all members of a class or object    
 class   People (object):  def  __init__   =  " alex  "   self.age  = 45obj  =  people ()  print  (Obj.__dict__  ) output: {  " name   ": "  alex  , "  age   ' : $ 
7. __str__If the __str__ method is defined in a class, the return value of the method is output by default when the object is printed.
class people (object):     def __init__ (self):         " Alex "          =    def __str__ (self):         return  = people ()print(obj) output: Alex
8. __getitem__, __setitem__, __delitem__

Used for index operations, such as dictionaries. Each of the above represents the acquisition, setting, and deletion of data

Reflection

The following 4 methods are used to map or modify the state, properties, and methods of a program when it is run

classFoo (object):def __init__(self): Self.name='Alex'    deffunc (self):Print("is OK")        #return ' func 'obj=Foo ()# # # Check if you have members # # #Print(Hasattr (obj,'name'))Print(Hasattr (obj,'func'))# # # # Get members # #Print(GetAttr (obj,'name')) getattr (obj,'func')()# # # # Set Members # #SetAttr (obj,' Age', 18) setattr (obj,'Show',LambdaNum:num + 1)Print(GetAttr (obj,"Show") (1))# # # # # Delete Members #Delattr (obj,'name') delattr (obj,'func')
Output:
True
True
Alex
is OK
2

Dynamic Import Module

Import__import__('import_lib.metaclass'#  This is the interpreter's own internal use of the #importlib.import_module (' Import_lib.metaclass ') #与上面这句效果一样, the official proposal with this 

Python faces object programming

Related Article

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.