At what point do methods in Python acquire a get
property? —As soon as they're defined in the class? Why does Python let me define a method without any arguments (not even a first self
argument)?
I know how to use classmethod
and staticmethod
, and I know that they're built-in functions, but what happens to a function that is so-decorated?
Essentially, I'm wondering about the "magic" that happens between class definition and class construction.
The class method takes cls (class) as first argument. The static method does not take any specific parameter. Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class.
If anything not using the decorator gives you a method that is more "static" because you can't even call it from an instance object. When you use @staticmethod you can call the method from both the class and class instance objects.
@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It's definition is immutable via inheritance. @classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance.
Check this out.
http://docs.python.org/howto/descriptor.html#static-methods-and-class-methods
You can also take a look at the source code for class and static method objects, in funcobject.c:
http://hg.python.org/cpython/file/69b416cd1727/Objects/funcobject.c
Class method object definition starts on line 694, while static method object definition starts on line 852. (I do find it kind of funny that they have items titled "method" in funcobject.c when methodobject.c also exists.)
For reference, from the first link in @JAB's answer
Using the non-data descriptor protocol, a pure Python version of staticmethod() would look like this:
class StaticMethod(object): "Emulate PyStaticMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): return self.f
...
Using the non-data descriptor protocol, a pure Python version of classmethod() would look like this:
class ClassMethod(object): "Emulate PyClassMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, klass=None): if klass is None: klass = type(obj) def newfunc(*args): return self.f(klass, *args) return newfunc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With