Reputation: 1077
Well, I guess that my question was already asked before, but I don't really know which terms to use to search for it, so apologize if this is a duplicate.
My question is how to call a method from the class which creates an instance of the current class? For example we have:
class First:
def __init__(self):
self.text = "This is a text in First class"
self.second = Second()
class Second:
def __init__(self):
print "How to show self.text from First?"
The way I'm doing this right now is to pass self
from class First
as an argument when initiating the Second
class, self.second = Second(self)
but I'm not sure if this is the right way. Also I found that it this could be possible by making Second
a subclass of First
, but I'm still not sure if this is the right way.
Could you help me with an answer? Thank you
Upvotes: 1
Views: 103
Reputation: 14873
This is how you can do it:
class First:
def __init__(self):
self.text = "This is a text in First class"
self.second = Second(self)
class Second:
def __init__(self, first):
self.first = first
print "How to show self.text from First?"
print self.first.text
Objects that know each other in this way and use each others attributes, I fear, are likely to violate law of demeter or make it hard to distinguish each other. And to distinguish them is very important for writing "good" classes. So handle it with care!
Other solution: pass text:
class First:
def __init__(self):
self.text = "This is a text in First class"
self.second = Second(self.text)
class Second:
def __init__(self, text):
self.text = text
print "How to show self.text from First?"
print self.text
This is also quite ok. I would like it more than the first solution. But when there are more arguments to come, text1, text2, text3, ... than this could be a new object.
class First(object):
@property
def text(self):
"get text from self.second"
return self.second.text
def __init__(self):
self.second = Second("This is a text in First class")
print self.text
class Second:
def __init__(self, text):
self.text = text
print "How to show self.text from First?"
print self.text
I think this is also quite a good solution for synchronising the text. But I can not think of an example where I really needed it.
Upvotes: 3