In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is Python's calling mechanism". In daily operation, I believe many people have doubts about what Python's calling mechanism is. Xiaobian consulted all kinds of materials and sorted out simple and easy operation methods. I hope to help you answer the question of "what is Python's calling mechanism"! Next, please follow the small series to learn together!
The following code will report an error, why?
class A(object): x = 1 gen = (x for _ in xrange(10)) # gen=(x for _ in range(10))if __name__ == "__main__": print(list(A.gen))
answer
This problem is a variable scope problem, where gen=(x for _ in xrange(10)) is a generator, where variables have their own set of scopes, isolated from the rest of the scope space. So, NameError: name 'x' is not defined, so what's the solution? The answer is lambda.
class A(object): x = 1 gen = (lambda x: (x for _ in xrange(10)))(x) # gen=(x for _ in range(10))if __name__ == "__main__": print(list(A.gen)) decorator
described
I want to write a class decorator to measure function/method runtime
import timeclass Timeit(object): def __init__(self, func): self._ wrapped = func def __call__(self, *args, **kws): start_time = time.time() result = self._ wrapped(*args, **kws) print("elapsed time is %s " % (time.time() - start_time)) return result
This decorator can run on ordinary functions:
@Timeitdef func(): time.sleep(1) return "invoking function func"if __name__ == '__main__': func() # output: elapsed time is 1.00044410133
But running in the method will report errors, why?
class A(object): @Timeit def func(self): time.sleep(1) return 'invoking method func'if __name__ == '__main__': a = A() a.func() # Boom!
If I insist on using class decorators, how should I modify them?
answer
After using class decorators, the corresponding instance is not passed to the__call__method during the call to func function, causing its mehtod to be unbound , so what is the solution? descriptor height
class Timeit(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print('invoking Timer') def_get__(self, instance, owner): return lambda *args, **kwargs: self.func(instance, *args, **kwargs)Python invocation mechanism
described
We know that the__call__method can be used to overload parenthesis calls, okay, so that's it? Naive!
class A(object): def __call__(self): print("invoking __call__ from A! ")if __name__ == "__main__": a = A() a() # output: invoking __call__ from A
Now we can see that a() seems equivalent to a.__ call__() , looks very Easy right, OK, now I want to die, and wrote the following code,
a.__ call__ = lambda: "invoking __call__ from lambda"a.__ call__()# output:invoking __call__ from lambdaa()# output:invoking __call__ from A!
Please explain why a() does not call a.__ call__() (This question was proposed by USTC Prince Bo)
answer
The reason is that in Python, the built-in special methods of new classes and the attribute dictionary of instances are isolated from each other. For details, please see the Python official documentation for this case.
For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object's type, not in the object's instance dictionary. That behaviour is the reason why the following code raises an exception (unlike the equivalent example with old-style classes):
At the same time, officials also gave an example:
class C(object): passc = C()c.__ len__ = lambda: 5len(c)# Traceback (most recent call last):# File "", line 1, in # TypeError: object of type 'C' has no len()
Returning to our example, when we are executing a.__ call__=lambda:"invoking __call__ from lambda", it is true that when we are in a.__ dict__adds a new item with key__call__, but when we execute a(), because it involves a call to a special method, our call process will not change from a.__ dict__looks for attributes from tyee(a).__ dict__ Therefore, the situation described above will occur.
descriptor
described
I wanted to write an Exam class whose attribute math is an integer [0,100] and throws an exception if it is assigned outside this range, so I decided to implement this requirement with descriptors.
class Grade(object): def __init__(self): self._ score = 0 def __get__(self, instance, owner): return self._ score def __set__(self, instance, value): if 0
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.