Reputation: 445
I have a setup that looks as following:
def docstring_formatter(func):
func.__doc__ = func.__doc__.format(class_name=func.__self__.__class__.__name__) #this does not work
return func
class A:
@docstring_formatter
def my_function(self):
"""I am a function of class {class_name}"""
print("test")
class B(A):
pass
docstring = getattr(B.my_function, "__doc__")
>>> AttributeError: 'function' object has no attribute '__self__'
I would like to access the actual class name that the instance of my_function belongs to. Since I am not instantiating the class I when I am using the help()
function, the __self__
property is not instantiated yet and I can also not make use of the functools.wraps
function. I would like to find a way to also extract the string B
or B.my_function
when being passed a my_function
object that could either belong to A()
or B()
.
Upvotes: 0
Views: 53
Reputation: 71464
Given the code:
class A:
def my_function(self):
print("test")
class B(A):
pass
b = B()
The my_function
object has a self
binding to the object you took it from, which is a B
, so you can do:
>>> b.my_function.__name__
'my_function'
>>> b.my_function.__self__.__class__.__name__
'B'
Upvotes: 2