Reputation: 135
I have two classes whom I need to be able to talk to each other, mainly one taking data from the other. I omitted everything that was not needed.
class dog(object):
def __init__(self,name):
self.name = name
def getOwner(self):
return self.name
class shelter(object):
def getName(self,dogName):
return dogName.getName()
doggy = dog("Rover")
animalHouse = shelter()
print animalHouse.getName("rover")
The only thing that returns is AttributeError: 'shelter' object has no attribute 'getName'
So how do I go about using the getName function from the dog class inside my shelter class?
Upvotes: 0
Views: 121
Reputation: 25954
Your approach really isn't OOP. What's the point of shelter
? You could just invoke getOwner
directly on the doggy
instance. Think about the physical realities of the objects you're dealing with. You have a dog
and a shelter
. How does the shelter interact with the dog?
The easiest way is to put one in there. So write that method. Let's give your shelter a resident
attribute:
def put(self,dog):
self.resident = dog
Now, it's best to have your shelter
always have that attribute defined, so let's do that in the initializer:
def __init__(self):
self.resident = None
And while we're at it, let's give ourselves the ability to specify the resident at the time when we create the shelter:
def __init__(self,dog=None):
self.resident = dog
This is making use of the "default attribute" feature of python. You can specify that argument, or not; it defaults to None
if you don't. If this is confusing, you can skip this step.
Given all that (and having put
a dog
in there), now we have a shelter
that contains None
or a dog
. Let's write your getName
method now.
def getName(self):
if self.resident:
return self.resident.getOwner() #this method is questionably named, but you wrote it
else:
return 'nobody home!'
Other comments: your classes should be named starting with Uppercase letters, and your methods should favor underscores to separate words as opposed to using mixedCase. So Shelter
for the class, and get_name
for the method. This is according to python naming conventions, see PEP 8 for all the gory details. :)
Upvotes: 0
Reputation: 28252
You didn't specify the getName
function. I think you want to declare getName
instead of getOwner
in the dog
class there, and you need to pass the instance of dog
to the function.
class dog(object):
def __init__(self,name):
self.name = name
def getOwner(self):
return self.name
class shelter(object):
def getName(self,dogName):
return dogName.getOwner()
doggy = dog("Rover")
animalHouse = shelter()
And finally:
#Pass the instance!
print animalHouse.getName(doggy)
Upvotes: 1