0

I am playing around with classes and I want to do the following:

class Hi (object):
     def __init__(self, bloop):
          self.bloop = bloop
thing = Hi("bloop")
name = input("Input a thing") # Let`s assume you input thing
print(name.bloop)

What I want it to do is for it to print "bloop" because you entered thing and it gets bloop from thing kinda like thing.bloop.

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
JohnyNich
  • 1,221
  • 3
  • 14
  • 23

1 Answers1

0

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.

deepbrook
  • 2,523
  • 4
  • 28
  • 49