Reputation: 19
I created a class: Hopper So that first_rabbit=Hopper('Thumper')
def __init__(self,name):
self.name=name
number_hops=10
self.number_hops=number_hops
def __repr__(self):
return (self.name + str(self.number_hops))
However, outside of the class, I use a function: jumping contest(first, second): Where the parameters would be rabbits (ie: Hopper('Thumper'))
In that function is there a way to isolate just the name like 'Thumper' so that I can print info?
Upvotes: 0
Views: 53
Reputation: 1897
You could actually go one step further in the built in attributes and use the name attribute. It would be like this:
def __init__(self,name):
self.__name__=name
number_hops=10
self.number_hops=number_hops
def __repr__(self):
return self.__name__
This would not really do anything differently, but the attribute name is there for this purpose, so it is probably best to use it. Alternatively, because you probably want to keep the repr that tells you both peices of information, so instead of accessing it by
print(rabbit)
than you would use
print(rabbit.__name__)
or just make a second function, like
def name(self):
return self.__name__
Upvotes: 1
Reputation: 17466
def __str__(self):
return self.name
And you can invoke it with
print(first_rabbit)
Upvotes: 0