【问题标题】:python class instance method call from another class instance从另一个类实例调用python类实例方法
【发布时间】:2015-06-10 09:17:20
【问题描述】:

我有一个关于 python 类的快速问题。 以下是设置: 我有一个类作为“策划者”类,其中包含其他类的各种实例。现在这些类需要调用另一个类的方法,但我不知道该怎么做。例如:

class mastermind(object):

    def __init__(self):
        self.hand = hand()

    def iNeedToCallThisMethod(self, funzies):
        print funzies

class hand(object):

    def __init(self):
        pass #here should be a call to the mastermind instance's method

example = mastermind()

希望你们能帮我解决这个问题,我的大脑正在冒热气!非常感谢!

【问题讨论】:

    标签: python class python-2.7 oop methods


    【解决方案1】:
    class hand(object):
    
        def __init(self, other_class):
            #here should be a call to the mastermind instance's method
            other_class.iNeedToCallThisMethod()
    m_m = mastermind()
    example = hand(m_m) # passes mastermind to new instance of hand
    

    我只是像上面那样传递对象

    【讨论】:

    • 你错了,你需要两个对象之间的引用。
    • 你能详细说明我相信我发布的内容是正确的@MalikBrahimi
    • iNeedToCallThisMethod 是一个实例方法,因此不能像您发布的那样直接使用 mastermind 类调用。 mastermind.iNeedToCallThisMethod() 只对类方法和静态方法有效。
    • 我相信您误认为mastermind 是对mastermind 类的调用,但它实际上是对传递给类的参数的调用。我应该更清楚,但代码工作正常。我已将 mastermind 更改为 other_class
    • 是的!很抱歉,完全没有意识到这一点。变量名让我失望
    【解决方案2】:

    如果要调用mastermind的方法,需要有引用。

    例如

    class mastermind(object):
        def __init__(self):
            self.hand = hand(self)
    
        def iNeedToCallThisMethod(self, funzies):
            print funzies
    
    class hand(object):
        def __init__(self, mastermind)
            mastermind.iNeedToCallThisMethod('funzies')
    

    【讨论】:

    • 谢谢!效果很好!但是,如果我将 Mastermind 实例保存到另一个实例中,是否会占用更多资源?还是真的只是一个参考?
    • 在我给出的示例中,您甚至没有保存实例 - 该方法是在提供的参数上调用的。但即使你确实保存了它,它也只是一个参考,所以除非你有几十万手,否则没有理由担心它。
    【解决方案3】:

    如果您需要从hand__init__ 调用iNeedToCallThisMethod,您应该将该方法放在该类中。

    但是,您可以使用classmethod

    class mastermind(object):
       def __init__(self):
            self.hand = hand()
    
       @classmethod
       def iNeedToCallThisMethod(cls, funzies):
            print funzies
    
    class hand(object):
       def __init__(self):
            mastermind.iNeedToCallThisMethod('funzies')
    
    example = mastermind()
    

    【讨论】:

      【解决方案4】:

      两个对象都需要相互引用,尝试将实例传递给构造函数。

      class Mastermind(object):
      
          def __init__(self):
              self.hand = Hand(self)
      
          def test_funct(self, arg):
              print arg
      
      
      class Hand(object):
      
          def __init(self, mastermind):
              self.mastermind = mastermind
              self.mastermind.test_funct()
      

      【讨论】:

        猜你喜欢
        • 2011-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多