Is there a way to access a class (where function is defined as a method) before there is an instance of that class?
class MyClass:
def method(self):
print("Calling me")
m1 = MyClass.method
instance = MyClass()
m2 = instance.method
print(m2.__self__.__class__) # <class 'MyClass'>
# how to access `MyClass` from `m1`?
For example I have m1
variable somewhere in my code and want to have a reference to MyClass
the same way I can access it from bound method m2.__self__.__class__
.
print(m1.__qualname__) # 'MyClass.method'
The only option I was able to find is __qualname__
which is a string containing name of the class.
The attribute
__self__
itself is annotated by Python when the function is bound to an instance and become a method. (The code to that is run somewhere when running the__get__
code in the function, but passing an instance different than None).So, as people pointed out, you have the option of getting the classname as a string by going through
__qualname__
. Otherwise, if the functions/methods for which you will need this feature are known beforehand, it is possible to create a decorator that will annotate their class when they are retrieved as a class attribute (in contrast to the native annotation which only takes place when retrieving then as an instance attribute):And on the REPL you can have this: