gpt4 book ai didi

python - 动态更改函数 __name__ 会抛出 AttributeError : 'method' object has no attribute '__name__'

转载 作者:行者123 更新时间:2023-12-01 01:03:09 25 4
gpt4 key购买 nike

我正在尝试编写一个类来捕获任何通用函数调用,然后尝试使用它进行一些操作。

作为示例,我尝试使用 here 中类似问题的答案.

但是,当我尝试通过分配 __name__ 属性来更改方法的名称时,它会抛出 AttributeError: 'method' object has no attribute '__name__' 错误。

我正在使用的代码,改编自 example above是:

class A():
def __init__(self):
self.x = 1 # set some attribute

def __getattr__(self,attr):
return self.__get_global_handler(attr)

def __get_global_handler(self, name):
# Do anything that you need to do before simulating the method call
handler = self.__global_handler
handler.__name__ = name # Change the method's name
return handler

def __global_handler(self, *args, **kwargs):
# Do something with these arguments
print("I am an imaginary method with name %s" % self.__global_handler.__name__)
print("My arguments are: " + str(args))
print("My keyword arguments are: " + str(kwargs))

def real_method(self, *args, **kwargs):
print("I am a method that you actually defined")
print("My name is %s" % self.real_method.__name__)
print("My arguments are: " + str(args))
print("My keyword arguments are: " + str(kwargs))

如果我注释更改方法名称的行(handler.__name__ = name # Change the method's name),效果很好:

>>> a.imaginary_method
<bound method A.__global_handler of <__main__.A object at 0x00000150E64FC2B0>>

>>> a.imaginary_method(1, 2, x=3, y=4)
I am an imaginary method with name __global_handler
My arguments are: (1, 2)
My keyword arguments are: {'x': 3, 'y': 4}

但是,如果我取消注释该行(以强制更改名称),我会得到:

>>> a.imaginary_method
[...]
AttributeError: 'method' object has no attribute '__name__'

我期望得到的是这样的:

>>> a.imaginary_method
<bound method A.imaginary_method of <__main__.A object at 0x00000150E64FC2B0>>

>>> a.imaginary_method(1, 2, x=3, y=4)
I am an imaginary method with name imaginary_method
My arguments are: (1, 2)
My keyword arguments are: {'x': 3, 'y': 4}

那么,有没有办法像这样动态更改方法的名称呢?非常感谢!

最佳答案

handler.__name__ = name 不起作用的原因是 handler 是一个绑定(bind)方法,即它是一个封装了对象的对象对函数和采用 self 值的实例的引用。您可以通过打印来确认这一点;它说“绑定(bind)方法”:

>>> a.imaginary_method
<bound method A.__global_handler of <__main__.A object at 0x00000150E64FC2B0>>

您可以通过__func__属性访问底层函数并更改其名称:

def __get_global_handler(self, name):
handler = self.__global_handler
handler.__func__.__name__ = name # Change the method's name
handler.__func__.__qualname__ = __class__.__qualname__ + '.' + name
return handler

但是,这种方法的问题在于,所有“虚构方法”实际上都引用相同的 __global_handler 方法。如果您尝试创建两个具有不同名称的方法,您会发现它们实际上具有相同的名称(因为它们是相同的方法):

a = A()
foo = a.foo
bar = a.bar

print(foo) # <bound method A.bar of <__main__.A object at 0x00000212AFCC7198>>
print(bar) # <bound method A.bar of <__main__.A object at 0x00000212AFCC7198>>

因此,更好的解决方案是每次创建一个新函数:

class MethodFactory:
def __getattr__(self, name):
def func(*args, **kwargs):
print("I am an imaginary method with name", name)
print("My arguments are:", args)
print("My keyword arguments are:", kwargs)

func.__name__ = name
func.__qualname__ = __class__.__qualname__ + '.' + name
return func

a = MethodFactory()
foo = a.foo
bar = a.bar
print(foo) # <function MethodFactory.foo at 0x00000238BDADC268>
print(bar) # <function MethodFactory.bar at 0x00000238BF8AB730>

如您所见,此实现的副作用是 foobar 是常规函数而不是绑定(bind)方法。如果由于某种原因,您必须返回绑定(bind)方法,您可以通过调用其 __get__ 手动将函数转换为绑定(bind)方法。方法:

class MethodFactory:
def __getattr__(self, name):
def func(self, *args, **kwargs):
print("I am an imaginary method with name", name)
print("My arguments are:", args)
print("My keyword arguments are:", kwargs)

func.__name__ = name
func.__qualname__ = __class__.__qualname__ + '.' + name
return func.__get__(self, type(self))

a = MethodFactory()
foo = a.foo
bar = a.bar
print(foo) # <bound method MethodFactory.foo of <__main__.MethodFactory object at 0x00000137BF0C29E8>>
print(bar) # <bound method MethodFactory.bar of <__main__.MethodFactory object at 0x00000137BF0C29E8>>

关于python - 动态更改函数 __name__ 会抛出 AttributeError : 'method' object has no attribute '__name__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55617568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com