I understand __class__ can be used to get the class of an object, it also can be used to get current class in a class definition. My question is, in a python class definition, is it safe just use __class__, rather than self.__class__?
#!/usr/bin/python3
class foo:
def show_class():
print(__class__)
def show_class_self(self):
print(self.__class__)
if __name__ == '__main__':
x = foo()
x.show_class_self()
foo.show_class()
./foo.py
<class '__main__.foo'>
<class '__main__.foo'>
As the codes above demonstrated, at least in Python3, __class__ can be used to get the current class, in the method show_class, without the present of "self". Is it safe? Will it cause problems in some special situations? (I can think none of it right now).
That is documented in the datamodel, so I believe it is safe/reliable.
From 3.3.3.5. Executing the class body:
Class variables must be accessed through the first parameter of instance or class methods, or through the implicit lexically scoped
__class__reference described in the next section.
From 3.3.3.6. Creating the class object:
__class__is an implicit closure reference created by the compiler if any methods in a class body refer to either__class__orsuper
It is true that the docs mention any methods, your foo.show_class is a function but perhaps not convincingly a method. However PEP 3135, which added this reference, is worded differently:
Every function will have a cell named
__class__that contains the class object that the function is defined in. ... For functions defined outside a class body,__class__is not defined, and will result in runtimeSystemError.
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