Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe just use __class__ in a python class definition

Tags:

python

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).

like image 225
xiepan Avatar asked Jul 31 '26 08:07

xiepan


1 Answers

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__ or super

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 runtime SystemError.

like image 132
wim Avatar answered Aug 02 '26 22:08

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!