0

我有这种代码。

class typeOne(self, obj):
  ....
  def run():
    # I want to call the funct() from typeTwo


class typeTwo(self, obj2):
  ...
  def funct():
    ...

class typePlayer(self, obj3):
  ...
  tT = typeTwo()
  ...
  tT.funct()
    .....

我想从 typePlayer 中调用的 typeOne 类中引用 typeTwo 类。

我试过这个。

class typeOne:
  ....
  mytT = typeTwo() # another probs here is that how can I get the 'obj2'?
  def run():
     mytT.funct()

但它创建了新的 typeTwo() 类,我不需要它,我只想调用现有的 typeTwo() 类而不创建一个,typeTwo() 类已由 typePlayer() 类执行。

有人对此有任何想法吗?

4

2 回答 2

0

如果一个类需要访问另一个类的特定实例,通常的解决方案是在实例化时将所需的实例传递给第一个类。例如:

class TypeOne(object):

  def __init__(self, myt2=None):
     self.myt2 = myt2 or TypeTwo()  # create instance if none given 

  def run():
     self.myt2.funct()

然后,像这样实例化两者:

myt2 = TypeTwo()
myt1 = TypeOne(myt2)

当然,既然TypeOne写的是TypeTwo如果没有传入一个实例,你也可以反过来做,让TypeOne创建TypeTwo实例然后从实例中获取它TypeOne

myt1 = TypeOne()   # creates its own TypeTwo instance
myt2 = myt1.myt2   # retrieves that instance for outside use
于 2013-09-15T14:46:09.440 回答
0

听起来您希望 TypeTwo 中的 funct() 是静态类:

class TypeTwo(object):
  ...
  @staticmethod
  def funct(x):
    ...

class TypeOne(object):
  ....
  def run():
    TypeTwo.funct(x)
于 2013-09-15T15:08:01.020 回答