classDecorator ():def __init__(self, f):Print('run in init ...') Self.f=Fdef __call__(self, A, b): Self.f (A, b) @Decorator#add = Decorator (add)defAdd (A, b):Print('A + B:', A +b) Add (10, 20)
Descriptor:
3.__SET__,__GET__,__DELETE__, what are they?
1). these 3 special functions to tell the truth I have not used to learn Python , and later in the reading of some advanced books only to discover its magical use!
is actually a descriptor concept inside the Python class. , descriptors allow you to customize what is supposed to be done when referencing an object property. These 3 special methods combine the descriptive protocol in Python:
-
__SET__: Called when designing a property
-
__get__: Called when a property is read
-
__DELETE__: Called when a property is deleted
A=a ()
A.x
>>
In __get__ <__main__. A object at 0x10089aa58> <class ' __main__. A ' >
Intercepted by the __get__ function, this time the incoming instance is a, and owner is his class is a
A.x=5
>>in __set__ <__main__. A Object at 0x101feba90> 5
When you assign a value to X, it is actually captured by __set__, at which point the incoming instance is a, and value is 5.
Del a.x
>>in __del <__main__. A Object at 0x1040c7a90>
When the x is deleted, it is actually captured by __del__, and this time the incoming instance is a
2). Some students say this descriptor is useless.
Here's a small example of how it can be done, like we're designing a class, and we want it to do type checking on their instance properties like c,c++:
P=person ()
P.name= ' Jack ' #名字必须是str
P.age=18 #年龄必须是int
P=person ()
P.name= ' Lily '
Print (' Name: ', p.name)
>>
Name:lily
If written
P.name=123
>>
Raise TypeError (' expected an {} '. Format (Self.your_type))
typeerror:expected an <class ' str ' >
Python also has a lot of esoteric points of knowledge, which are advanced content. It is said that Python is easy to master, if you want to understand the beauty of Python , we need to dig deep into its intrinsic characteristics, and deep into the internal language to analyze its internal mechanisms and mysteries! I said in the small dense circle Python has 3 major difficulties, I will write an article one after the introduction!
Python Small knowledge-__call__ and class decorators used in combination