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!
4 Answers 4
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')
2 Comments
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()
Comments
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()
Comments
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
6 Comments
iNeedToCallThisMethod is an instance method, so cannot therefore be called directly using the mastermind class, as you posted. mastermind.iNeedToCallThisMethod() would only be valid for class methods and static methods.mastermind was a call to the class mastermind but it was actually a call to a parameter being passed to the class. I should've made that clearer but the code works fine. I've changed mastermind to other_classExplore related questions
See similar questions with these tags.