Reputation: 31
I have a quick question regarding python classes. The following is the setup: I have one class as the "mastermind" class which contains various instances of other classes. Now these classes need to call a method of that other class, but I don't know how to do that. For example:
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()
Hope you guys can help me with that, my brain is steaming! Thanks a lot!
Upvotes: 2
Views: 20138
Reputation: 808
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
I'd just pass the object like above
Upvotes: -1
Reputation: 16711
Both object need a reference to one another, try passing the instance to the constructor.
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()
Upvotes: -1
Reputation: 2130
If you need to call iNeedToCallThisMethod
from the __init__
of hand
, you should probably put the method in that class.
However, what you want to do can be achieved using a 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()
Upvotes: 1
Reputation: 10197
If you want to call mastermind's method, you need to have a reference to it.
For example
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')
Upvotes: 9