Built-in method and polymorphic class day23_7.29

One. Polymorphism

  In real life, multi-state will be reflected. The water for this material, there are solid: ice, liquid: normal, gas: water vapor,

  In the program, which is the official definition: a respective plurality of different objects may be the same method, different results.

  In the python, polymorphism is not a special syntax, but a relationship between a characteristic, for example:

class A:
    def work(self):
        print('I am working in A')

    def name(self):
        print('i am A')

class B:
    def work(self):
        print('I am working in B')

    def name(self):
        print('i am B')

class C:
    def work(self):
        print('I am working in C')

    def name(self):
        print('i am C')

a=A()
b=B()
c=C()
def toge(obj):
    obj.work()

toge(a)
toge(b)
toge(c)
#I am working in A
#I am working in B
#I am working in C

  The above code were manufactured ABC three categories, three classes have different characteristics, also have the same features work, can be polymorphic, the unified management of the work so that the work which retained other characteristic.

  This approach is reflected in the interface, so in addition to the duck type may also be used to abstract classes and interfaces polymorphic.

  If this is not characteristic, the corresponding process requires three separate versions of the object ab.

two. Built-related objects

  1.isinstance

  Action: determining whether an object is an instance of a class: the isinstance (object class)

  This method can also be determined whether a certain type of data is the isinstance (data type)

class Person:
    def work(self):
        print('i am working ')

class book:
    def write(self):
        print('i can write')

def working(oop):
    if isinstance(oop,Person):
        oop.work()
    else:
        print('you are not Person')

ab=Person()
ac=book()
working(ab)
working(ac)
#i am working 
#you are not Person

  When an object does not have certain characteristics, can be used to determine whether isinstance function may be performed, so the program will not be given, may not be performed because the method does not exist.

  In addition, isinstance can also determine if a data is not a data type:

DEF the Add (A, B):
     IF the isinstance (A, int) and the isinstance (B, int):
         return A + B
     the else :
         return  ' is not an integer ' 

Print (the Add (2,44 ))
 Print (the Add ( ' ASD ' , 2 ))
 # 46 
# is not an integer

  2.issubclass (subclass, the parent class)

  The role of judge a sub-class is not a subclass of a parent class.

class Father:
    def name(self):
        print('i am father')

class Son(Father):
    def name(self):
        print('i am son')

class Wang:
    def name(self):
        print('i am wang ')

def test1(oop):
    if issubclass(type(oop),Father):
        oop.name()
    else:
        print('you are not my son')

s1=Son()
w1=Wang()
test1(s1)
test1(w1)
#i am son
#you are not my son

three. Magic function

  Such methods are generally used in the class.

  1.__str__

  This method is triggered when the object is converted to a string, and the object is an object originally form:

<__main__.Person object at 0x00000288BDA380B8>

  And this method obviously does not make sense, but for the principle print any data is first converted to a string form printed out, so, if after the definition of the method can print the object directly.

  In the process __str__ object parameters can be passed, a predetermined print format, such as:

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

    DEF  __str__ (Self):
         return  ' name% s, age S% ' % (the self.name, self.age ) 

p1 = the Person ( ' LZX ' , 18 )
 Print (p1)
 # name is lzx, age 18

  2 .__ del__

  This method is when the object is deleted, the implementation of the method:

class Person2:
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __del__(self):
        print('i am del')

a=Person2('lzx',123)
del a
print('over')
#i am del
#over

  When performing del a and is said to be, it will print iam del

  But if you do not execute del a statement, the program will automatically end, garbage collection will automatically delete unused objects recovered, even if do not write this sentence, will perform in the final statement.

  Easy file handling:

class File1:
    def __init__(self,file):
        self.file=open(file,'r',encoding='utf-8')

    def read(self):
        return self.file.read()

    def __del__(self):
        self.file.close()
        print('over')

ab=File1('test.py')
print(ab.read())

  At the end it is automatically closed operations on files.

  3.__call__

  When an object is called, execution of the function call is the object name + ()

class Test2:
    def __call__(self, *args, **kwargs):
        print('666')

ba=Test2()
ba()
#666

  4.__slots__

  This property is a property class, the class used for the memory optimization, when a class is defined __slots__ is, the space will be such that the class name is not created, the class can be used to create slots in the name of any attribute , no more and no less, so that we can reduce the effect of memory overhead.

  __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__ )

  Note, Person in __dict__ this time does not exist.

  5.getattr setattr delattr

  When getattr access point with the attribute of execution if the property does not exist

  When setting properties with the point setattr

  delattr with del objects executed at the property delete property

class Test3:
    def __getattr__(self, item):
        print('__getattr__')
        return 1

    def __setattr__(self, key, value):
        print('__setattr__')
        self.__dict__[key]=value

    def __delattr__(self, item):
        print('__delattr__')
        self.__dict__.pop(item)

abc=Test3()
print(abc.name)
abc.name='123'
print(abc.name)
del abc.name
print(abc.name)
#__getattr__
#1
#__setattr__
#123
#__delattr__
#__getattr__
#1

  First, in addition to the use of super class method inherited his father run the program to realize the function, the basic principle setattr is to add the key to the dictionary __dict__ name of space, called when setting properties. And also delete the namespace dictionary keys pop up, the way the function is executed statement.

  Getattr and, when this value can be acquired through the point, the return value, when the value is not found in the return value is returned

  getattribute

  When the class has getattribute method, before getting the value it will give priority to execute the function, if it acquires the property, it will return the value, if not found, it will call getattr method.

class Test3:
    def __getattr__(self, item):
        print('__getattr__')
        return 1

    def __getattribute__(self, item):
        print('__getattribute__')
        return super().__getattribute__(item)


abc1=Test3()
# abc1.name=123
print(abc1.name)
#__getattribute__
#__getattr__
#1

  6.getitem, setitem, Delite

  When the above-described class retransmission method, using [] gets its value, the function will be triggered.

class Test4:
    def __getitem__(self, item):
        print('__getitem__')
        return self.__dict__[item]

    def __setitem__(self, key, value):
        print('__setitem__')
        self.__dict__[key]=value

    def __delitem__(self, key):
        print('__delitem__')
        del self.__dict__[key]

abc4=Test4()
abc4['name']=22
print(abc4['name'])
del abc4['name']
print(abc4['name'])
#__setitem__
#__getitem__
#22
#__delitem__

  Can understand.

  Example: Let an object supports both point value, and support [] values:

class MyDict(dict):

     def __getattr__(self, key):
         return self.get(key)
    
     def __setattr__(self, key, value):
         self[key] = value
    
     def __delattr__(self, item):
         del self[item]

  In this class, the first class inherited dict method, may be used such that the object attribute dictionary, then return the value of its operating point.

  7. The operator overloading (__gt __, __ lt __, __ eq__)

  is compared gt large, the function to run between the objects

  lt is relatively small between objects, run the function

  Eq is equivalent when compared between objects, run the function

  Originally between objects is not supported by the comparison operators (equal to be compared)

class Test6:
    def __init__(self,name,age):
        self.name=name
        self.age=age

a=Test6('lzx',6)
b=Test6('zzp',3)
print(a>b)
#报错

  Also compare two objects are the same when comparing equal.

  The use of relatively gt lt property value or between objects may be achieved:

class Test6:
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __gt__(self, other):
        if self.age>other.age:
            return True
        return False

    def __lt__(self, other):
        if self.age<other.age:
            return False
        return True

    def __eq__(self, other):
        if self.age==other.age:
            return 123
        return 321

a=Test6('lzx',6)
b=Test6('zzp',3)
print(a<b)
print(a==b)
#True
#321

  Of course, and between gt lt need only one is enough. If the symbol is different interpretations are automatically exchanged positions of two objects.

four. Iterator

  For a class or object, to an iterator, in need thereof defines two methods: __ item__ and __next__.

class Dd:
    def __init__(self,max):
        self.max=max
        self.count=0

    def __iter__(self):
        return self

    def __next__(self):
        if self.count<self.max:
            self.count+=1
            return self.count
        else:
            raise StopIteration

for i in Dd(10):
    print(i)

  Dd to make an iterator, Dd's role is to input the number of 1-10, when calling the class execution in the next sentence, using StopItIreration be an exception is thrown, stop the program, to prevent infinite loop.

  With this range can mimic the function:

class Myrange:
    def __init__(self,min1,max1,step=1):
        self.min1=min1-1
        self.max1=max1-1
        self.step=step

    def __iter__(self):
        return self

    def __next__(self):
        if self.min1<self.max1:
            self.min1+=self.step
            return self.min1
        else:
            raise StopIteration

for i in Myrange(0,10,2):
    print(i)

  Above, range to meet the left and right opening and closing principle, the default step step 1, it does not matter if not pass, except that the start number must pass.

  It is possible to have the __iter __, __ class two methods as a next__ iterator.

Fives. Operational context

  In fact, the application context operations already, open the image file is written in the context of the operation, when used with a file operation will get a file handle, to handle the operation, even if later forget to turn off the file link, the final program will automatically help you shut down, the principle is the exit function in the open class to help you close the file.

  When performing with the statement, the statement will be executed first enter, if run properly, run the exit statement, when an abnormality occurs in the process enter run, it will run immediately exit statement , and pass exception information.

class Text7:
    def __init__(self,file):
        self.file=file

    def __enter__(self):
        print('enter===')
        self.f=open(self.file)
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit===')
        print(exc_type, exc_val, exc_tb)
        self.f.close()

with Text7('test.py') as m:
    print(m.read())

  Text7 is a low with the open operation, wherein:

  enter the file handle as the return value to the class.

  In the exit in exc_type, exc_val, exc_tb, three parameters is the abnormal return information (including the type of error. The error message Error tracking information).

  Tips: exit also returns a value, returns a Boolean value (True, False), when the program ends properly, there is not much impact,

      When an exception occurs the program, if the return value is true, the exception will be processed, while if the return False. Exception will be retained.

 

Guess you like

Origin www.cnblogs.com/LZXlzmmddtm/p/11266139.html