![](/img/trans.png)
[英]Python: How to call an instance method from a class method of the same class
[英]python class instance method call from another class instance
我对python类有一个快速的问题。 以下是设置:我有一个类作为“ mastermind”类,其中包含其他类的各种实例。 现在这些类需要调用另一个类的方法,但是我不知道该怎么做。 例如:
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()
希望你们能帮助我,我的大脑在蒸腾! 非常感谢!
如果要调用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')
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
我只是像上面那样传递对象
如果您需要从__init__
的hand
调用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()
这两个对象都需要相互引用,请尝试将实例传递给构造函数。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.