gpt4 book ai didi

python - 在 Python 中,是否可以调用类 A 的实例方法,但传入类 B 的实例?

转载 作者:太空狗 更新时间:2023-10-29 22:07:21 25 4
gpt4 key购买 nike

为了重用一些被定义为不同类的实例方法的现有代码,我想做如下事情:

class Foo(object):
def __init__(self):
self.name = "Foo"

def hello(self):
print "Hello, I am " + self.name + "."

class Bar(object):
def __init__(self):
self.name = "Bar"


bar = Bar()
Foo.hello(bar)

但这会导致:

TypeError: unbound method hello() must be called with Foo instance as first argument (got Bar instance instead)

这样的事情可能吗?


我应该清楚我知道这是个坏主意。显然,真正的解决方案是进行一些重构。我只是觉得一定有办法,事实证明是有的。

感谢评论。

最佳答案

看起来像这样:

Foo.hello.im_func(bar)

Hello, I am Bar.

我想我需要阅读 this有点难...

关于python - 在 Python 中,是否可以调用类 A 的实例方法,但传入类 B 的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/784331/

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