How about storing thing
in a dict
:
class Hi:
def __init__(self, bloop):
self.bloop = bloop
things = {'thing': Hi('bloop')}
name = input("Input a thing") # Let`s assume you input 'thing'
try:
print(things[name].bloop)
except KeyError:
print("Sorry, I dont know that thing :(")
There are, of course, other ways to call an attribute of a class. You could implement a __call__()
method, which allows you to call the class instance like a function, and in your case return .bloop
:
class Hi:
def __init__(self, bloop):
self.bloop = bloop
def __call__(self):
return self.bloop
things = {'thing': Hi('bloop')}
name = input("Input a thing") # Let`s assume you input 'thing'
try:
print(things[name]())
except KeyError:
print("Sorry, I dont know that thing :(")
This way, you can rename your attribute later, or return another attribute (or do something entirely different altogether), without having to replace .bloop
in your main python file.
A third way, which directly relates to your question's title calling attributes from[of] classes in Python
: you can use the @Property
decorator to make your .bloop
attribute callable like a function like so:
class Hi:
def __init__(self, bloop):
self.bloop = bloop
@Property
def bloop():
return self.bloop
@bloop.setter
def bloop(self, new_value)
self.bloop = new_value
things = {'thing': Hi('bloop')}
name = input("Input a thing") # Let`s assume you input 'thing'
try:
print(things[name].bloop())
except KeyError:
print("Sorry, I dont know that thing :(")
To fully understand the Property
decorator, I recommend this article.
Btw, according to the tags
on your question, you're using Python3.x
- you don't have to declare that your class inherits from Object
in Python3 and later.