在Python中,你可以调用A类的实例方法,但是传递B类的实例? [英] In Python, can you call an instance method of class A, but pass in an instance of class B?

查看:305
本文介绍了在Python中,你可以调用A类的实例方法,但是传递B类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class Foo(object):
def __init __(self):
self.name =Foo

def hello $ b printHello,I am+ self.name +。

class Bar(object):
def __init __(self):
self.name =Bar


bar = ()
Foo.hello(bar)

但结果是:


TypeError:未绑定的方法hello()必须使用Foo实例作为第一个参数来调用


< blockquote>

这样的东西可能吗?






我知道这是一个坏主意。显然,真正的解决方案是一点重构。



感谢您的意见。

解决方案

看起来像这样:

  Foo.hello.im_func $ b  




您好,我是Bar。


< blockquote>

我想我需要阅读很难...


In the interest of reusing some existing code that was defined as an instance method of a different class, I was tying to do something like the following:

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)

but that results in:

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

Is something like this possible?


I should have been clear that I know this is a bad idea. Obviously the real solution is a bit of refactoring. I just figured there must be a way, and it turns out there is.

Thanks for the comments.

解决方案

Looks like this works:

Foo.hello.im_func(bar)

Hello, I am Bar.

I guess I need to read a this little harder...

这篇关于在Python中,你可以调用A类的实例方法,但是传递B类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆