OPP state as much as three characteristics

First, the concept of polymorphism

1. What is polymorphism?

A thing with a variety of forms, the object is the face of a variety of state

The official explanation: a plurality of objects of different classes can respond to the same method, different results

He emphasized: polymorphism is not a special syntax, but a state, characteristics, i.e., a plurality of objects using the same method.

2. advantage

1. increase the flexibility of the program

2. increase the program's scalability

3. For users, the talk of the difficulty of use

3. To achieve polymorphism

Interfaces, abstract classes, duck type, could be written with multi-state code,

The simplest is the type of duck

4. Example:

1 . To manage duck and goose, how best to facilitate the management?
class Chicken:
     DEF Speak (Self):
         Print ( ' chirp sets ' ) 

    DEF the spawn (Self):
         Print ( ' the eggs ' ) 


class Duck:
     DEF Speak (Self):
         Print ( ' Gaga Ga ' ) 

    DEF the spawn (Self) :
         Print ( ' the duck ' ) 

class of Er:
     DEF Speak (Self):
         Print ( ' goose goose' ) 

    DEF the spawn (Self):
         Print ( ' Chardin ' ) 

J = Chicken () 
Y = Duck () 
E = of Er () 


DEF Mange (obj): 
    obj.spawn () 

Mange (J) 
Mange (Y) 
mange (e) 


example Problems: animals are chickens, ducks, which are provided with laying skills, it is possible to define a unified interface 
to use DEF Mange (obj): 
    obj.spawn ()


    
     2 another example:. 
a = 10 
B = ' 10 ' 
C = [10 ] 


Print (type (A))
 Print(of the type (b))
 Print (of the type (c)) 


# A, b, c have their own type 
# This is the common denominator

 

 

Two, OPP related built-in functions

1.inistance

Determine whether an object is an instance of

A parameter: the object to be judged

Parameter II: To determine the type of

example:

DEF add_num (a, b):   # where a, b is a parameter 

    IF the isinstance (A, int) and the isinstance (B, int):   # where a, b are two parameters 
        return A + B
     return None 

Print ( add_num (20,10))   # print the results: 30

2.issubclass

Determining whether a class is a subclass of another class of

A parameter: subclass

Two parameters: parent

example:

class Animal:
     DEF EAT (Self):
         Print ( ' animals to eat ' ) 


class Dog (Animal):
     DEF EAT (Self):
         Print ( ' dog eat bones ' ) 


class Tree:
     DEF Light (Self):
         Print ( ' plant photosynthesis ' ) 

Dog = Dog () 
Tree = Tree () 

DEF Manage (obj):
     IF issubclass (type (obj), Animal):   # determines whether the class is a subclass of Animal, if the print target content, otherwise return to the results: not animals
        obj.eat ()
     the else :
         Print ( ' not animals ' ) 


the Manage (Dog)   # dog bones to eat 
the Manage (Tree)   # are not animals

 

Third, the class magic function

1.str

Format Method: In print outside the class object is being called

Formatting outside the direct printing of such a string representation of the results

str will be when the object is converted to a string, the result of this conversion is the return value of the function

Usage scenarios: We can use this function to customize the object is to print format

class A:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __str__(self):
        return 'my name is %s,my age is %s'%(self.name,self.age)

a = A('jack',18)
print(a)  

# 打印结果:my name is jack,my age is 18

2.del

Destructor: the moment is called the object to be consumed before being consumed can do something

del will be called when the object is consumed on behalf of self, or some resources will persist (save to database file members)

Execution timing: Manually delete the object immediately executed or will execute automatically when the program ends

Usage scenarios: When your object in use, open the resource does not belong to the interpreter

example:

class FileTool:
     "" " class file read and write operations to simplify " "" 

    DEF  the __init__ (Self, path): 
        self.file = Open (path, " RT " , encoding = " UTF-. 8 " ) 
        self.a 100 = DEF the Read (Self):
         return self.file.read () # where you can determine a thing, this object is certainly not used so you can rest assured that the file is closed and asked the DEF __del__ (Self): 
        self.file.close ( ) 
Tool = FileTool ( " a.txt " )
 Print (tool.read ())

    

    
     

3.call

Execution timing: automatically executed when the calling object (the object that is in brackets)

class A:
    def __call__(self, *args, **kwargs):
        print("call run")
        # print(args)
        print(kwargs)
​
a = A()
a(1,a=100)

4.slots

This property is a class attribute for the object to optimize memory usage

Optimized principle: the original is not a fixed number of attributes, become fixed

This interpreter does not create a namespace for this object, so dict did not,

So as to achieve the effect of reducing memory overhead

Will cause the object of this class can not add new attributes if there is a class when slots

class the Person: 

    __slots__ = [ " name " ]
     DEF  __init__ (Self, name): 
        self.name = name 

the p- = the Person ( " JCK " ) 

# to view memory usage 
# Print (sys.getsizeof (the p-)) 
# p.age = unable to add # 20 

# dict no 
# Print (the p-.__ dict__)

5.getattr setattr delattr

If the property is not executed when there is access to the property with getattr point 
setattr set point when a property
delattr with del objects. execution of these functions reflects the python interpreter deleted property when property is how to achieve a point to visit the property getattribute function is used to obtain the property
at the time of acquiring property if there is getattribute the first execution of the function, if you did not get the property continue to call getattr function, if you get a direct return

6. [] of real principle

GetItem setitem Delite

Any symbol, the interpreter will be interpreted as a special meaning; for example.

getitem: perform when used to acquire properties brackets

setitem: when performed using brackets set properties

delitem: When executed in square brackets to delete property

 

Fourth, the operator overloading

When a series of methods we use a certain symbol, Python interpreter will be a symbol definition for the meaning of, and call the corresponding handler, when we need to compare rules defined objects, can cover greater than or equal in subclasses like

example:

class Student:
     DEF  the __init__ (Self, name, Age, height): 
        the self.name = name 
        self.age = Age 
        self.height = height 

    # DEF __gt __ (Self, OTHER): # is greater than the number __gt__; __ lt__ is less than No. (only need to implement a can) 
    #
     #      return self.height <other.height # Self is itself, that is stu1, other means are STU2 

    DEF   __eq__ (Self, OTHER):
         return self.height == OTHER. height   # returns True or False depending on the print base 


STU1 = Student ( ' Jack ' , 18,178 ) 
STU2 = Student (' Lucy ' , 17,178 )
 Print (STU1)
 Print (STU2) 


# Print (STU1> STU2) greater than the comparison # (less than the comparison may be performed) 
Print (STU1 == STU2)   # equals compare



In the above code, other refers to the object involved in another comparison,

 
 

Any one of those above and below can, if different symbol interpreter automatically switching the position of two objects

 

Fifth, the iterator protocol

Iterators are objects that have __iter__ and __next__ we can add these two methods for the object to make the object becomes an iterator
class MyIRange:
    def __init__(self,start,end,step):  # step表示步长
        self.start = start
        self.end = end
        self.step = step
​
    def __iter__(self):
        return self
​
​
    def __next__(self):
        a = self.start
        self.start += self.step
        if a < self.end:
            return a
        else:
            raiseStopIteration   # returns an exception 
for i in MyIRange (1, 10, ):
     Print (i)

 

Sixth, the written message management

Written on paper: context

This concept belongs to language learning, referring to the meaning of a passage, to refer to the current scene that context

In python, the context can be understood as a section of code, a range of, for example, open files with open only valid in this context

It involves two methods:
1.enter

That enter the context

2.exit

It means exit context

 

class MyOpen(object):


    def __init__(self,path):
        self.path = path  # 路径

    def __enter__(self):
        self.file = open(self.path)  # 打开文件
        print("enter.....")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit...")
        # print(exc_type,exc_val,exc_tb)
        self.file.close()  # 关闭文件
        return True


MyOpen with ( ' a.txt ' ) m AS:
     Print (m.file.read ()) 
    
    
    when performing with statement, execution will first enter, when the execution code is completed after the exit, or the code will execute an exception is encountered immediately exit and pass the error message contains the type of error. the error message error tracking information 
    
    
    
    enter the function should return the object can have its own exit function return value is a bool type, indicating whether the exception is handled, appear only in context If an exception is useful to True means that, exceptions, and was handled False, an exception is not handled, the program will interrupt error

 



 

 

Guess you like

Origin www.cnblogs.com/xiongying4/p/11266299.html