sinvilla.blogg.se

Zen of python decoration
Zen of python decoration







Luckily, after some googling, I found this documentation on descriptors. So, I went to github to look for the source code for However, it is implemented inside the Python interpreter, in C., and I do not feel like writing a C-extension that much I can tell you. In the end, there is a much better solution to the problem. Also, the errors might be very non-descriptive or even confusing. The first parameter passed to the function will still be self, even if we call it something else. Isn't that a class-only method? It is close but not quite, as when creating a method with parameters it starts to get a bit more complicated. Now you might think the problem is solved, we have a method which can't be called from an instance. This is caused by python automatically passing the instance as the first argument to the function. Without the decorator the second call, the one using the instance, my_obj, would have crashed with a type error: TypeError: dev() takes 0 positional arguments but 1 was given.

zen of python decoration

First, let's look at an example of class M圜lass: def dev(): It, therefore, seems like the best place to start. This being the possibility to call it directly from the class without an instance. Also, we have which does one of the two features we want for class-only methods. The first rule in the Zen of Python is beatiful is better than ugly and using a decorator would be the most pretty solution. Maybe I could have a list of class-only functions and remove them from the instance as a part of the _init_ method?.Create a decorator similar to and Could meta-classes be used to solve this?.To start off I threw out some ideas for where to start: I would also like to explain my process for solving this problem, as I didn't really know from the start descriptors would be the solution. Spoiler, the cover-image is the entire implementation.

zen of python decoration

#Zen of python decoration how to#

I think this is quite a niche feature, but it is a neat example of how to implement a simple descriptor. A class-only method should only be callable as a static method and not work from an instance of the class.

zen of python decoration

I ran across a post asking how you can create class-only methods in Python.







Zen of python decoration