Detecting whether an object exists in this document
# -*- coding: utf-8 -*- import sys x=10 obj1=sys.modules[__name__] print(hasattr(obj1,"x")) obj2=sys.modules[__name__] print(hasattr(obj2,"y"))
Dynamic introduced based on the reflected module
isinstance Checks whether the object is a class object is generated
# -*- coding: utf-8 -*- class Foo(object): pass obj = Foo() isinstance(obj, Foo)
issubclass (class1, class2) check whether class1 derived class is generated class2
# -*- coding: utf-8 -*- class Foo(object): pass class Bar(Foo): pass print(issubclass(Bar, Foo))
__getattribute__
When __getattribute__ and __getattr__ exist, it will only execute __getattrbute__, unless an exception is thrown __getattribute__ AttributeError in the implementation process both at the same time appear
# -*- coding: utf-8 -*- __author__ = 'Linhaifeng' class Foo: def __init__(self,x): self.x=x def __getattr__(self, item): print ( 'execution is that I')
def __getattribute__(self, item): print ( 'regardless of whether there is, I will execute') raise AttributeError ( 'ha') f1=Foo(10) Fl .X
# There are exceptions, but the program does not immediately collapse f1.xxxxxx
__getitem__,__setitem__,__delitem__
Attr writing point manner (above) related, related to the way the dictionary item (below) written.
# -*- coding: utf-8 -*- class Foo: def __init__(self,name): self.name=name def __getitem__(self, item): print(self.__dict__[item]) def __setitem__(self, key, value): self.__dict__[key]=value def __delitem__(self, key): print ( 'when del obj [key], I run') self.__dict__.pop(key) def __delattr__(self, item): print ( 'when del obj.key, I executed') self.__dict__.pop(item) f1=Foo('sb') f1['age']=18 f1['age1']=19 of the f1.age1 del f1['age'] f1['name']='alex' print(f1.__dict__)
String built-in functions related to rewrite
__str__,__repr__,__format__
# -*- coding: utf-8 -*- # Define different formats school name, school address, type of school format_dict={ 'Nat': '{obj.name} - {obj.addr} - {obj.type}', # school name - school address - School type 'Tna': '{obj.type}: {obj.name}: {obj.addr}', # School type: school name: School address 'Tan': '{obj.type} / {obj.addr} / {obj.name}', # type of school / school address / name of the school } class School: def __init__(self,name,addr,type): self.name=name self.addr=addr self.type=type # Can not find repr str went as a substitute def __repr__(self): return 'School(%s,%s)' %(self.name,self.addr) def __str__(self): return '(%s,%s)' %(self.name,self.addr) def __format__(self, format_spec): # if format_spec if not format_spec or format_spec not in format_dict: format_spec='nat' fmt=format_dict[format_spec] return fmt.format(obj=self) s1 = School ( 'oldboy1', 'Beijing', 'private') print('from repr: ',repr(s1)) print('from str: ',str(s1)) print(s1) ''' str function or the print function ---> obj .__ str __ () repr or interactive interpreter ---> obj .__ repr __ () If __str__ is not defined, then it will use to replace the output __repr__ Note: The return value maybe method must be a string, or an exception is thrown ''' print(format(s1,'nat')) print(format(s1,'tna')) print(format(s1,'tan')) print(format(s1,'asfdasdffd'))
__slots__
# -*- coding: utf-8 -*- ''' What is 1 .__ slots__: class variable is a variable value may be a list, ancestral or iterables, may be a string (meaning all instances only one data attribute) 2. Introduction: use points essentially in the access attribute access class or object __dict__ attribute dictionary (dictionary class is shared, but each instance is independent) 3. Why __slots__: the dictionary takes up a lot of memory, if you have a few attributes of the class, but there are many examples, in order to save memory can be used to replace __slots__ instance __dict__ When you define __slots__, __ slots__ will be represented as an example the use of a more compact internal. Examples constructed by a small fixed-size array of, rather than for each instance a defined Dictionary, which is very similar with the tuple or list. __Slots__ attribute names listed in the internally mapped to the specified small scale this array. __Slots__ a bad place to use that we can not give Examples of adding new attributes, and use only those property names defined in the __slots__. 4. Note: __ slots__ many features are dependent on the ordinary dictionary-based implementation. In addition, the definition of the class after __slots__ no longer supports some common characteristics of the class, such as multiple inheritance. In most cases, you should Only those defined in the class are often used as a data structure to __slots__ such as the need to create millions of instances of a class of objects in the program. A common misunderstanding is that it can be about __slots__ package as a tool to prevent the user to add new attributes instances. Although __slots__ can achieve this purpose, but this is not its original intention. More is used as a memory optimization tool. ''' class Foo: __slots__ = 'x' #key=x,value=none f1 = Foo() f1.x = 1 # F1.y = 2 # error print (f1 .__ slots__) # print (f1 .__ dict__) f1 is no longer __dict__ class Bar: Where two key properties __slots__ = [ 'x', 'y'] # n Bar () nx, ny = 1, 2 #nz = 3 # error, there is no longer __dict__
__doc __ (description attribute specified is not defined by default)
# -*- coding: utf-8 -*- class Foo: 'I am the description' pass class Bar(Foo): pass print(Foo.__doc__) print (Bar .__ doc__) # This attribute can not be inherited by subclasses
__module__ when other documents from the introduction of classes, from which the object used to view a file in
__class__ introduction class from another file, object to see which one class which use a file from
__del__ destructor (when the object is released in the memory, automatically trigger the execution, do not generally define Python) __ del__ will only be triggered in the case of a solid column to be deleted
When delete a row trigger real
# -*- coding: utf-8 -*- class Foo: def __del__(self): print ( 'execute my friends') f1=Foo() of the f1 print('------->')
The entire program is finished release the memory
# -*- coding: utf-8 -*- class Foo: def __del__(self): print ( 'execute my friends') f1=Foo() print('------->')
__call__ objects parentheses execution (provided that the written __call__)
# -*- coding: utf-8 -*- class Foo: def __init__(self): pass def __call__(self, *args, **kwargs): print ( 'execution __call__') obj = Foo () # execute __init__ obj () # execute __call__
__next __, __ iter__ implement the iterator protocol
Example: Implementing Fibonacci number
# -*- coding: utf-8 -*- class Fib: def __init__(self): self._a=0 self._b=1 def __iter__(self): return self def __next__(self): self._a,self._b=self._b,self._a + self._b return self._a f1=Fib() print(f1.__next__()) print(next(f1)) print(next(f1)) for i in f1: if i > 100: break print('%s ' %i,end='\n')
Descriptor is a "binding behavior" of the object attributes in the descriptor protocol, a method which can charge property write access. These methods are GET (), SET (), Delete (). If any of these methods are defined in an object, the object is a descriptor. (This number is a special method, since the conversion is not shown double underlined)