0

I am trying to create a function that calls an attribute determined by what argument is passed.

class room:
    def __init__(self, length, bredth, depth):
        self.length = length
        self.bredth = bredth
        self.depth = depth

    def displaymeasurement(self, side):
        print(self.side)


kitchen = room(10, 20, 15)

room.displaymeasurement("depth")

This is an abstraction of the code I'm using as that's too convoluted. I have striven to match it to the code in question, and it does produce the same error message.

Traceback (most recent call last):
  File "/home/townsend/Documents/PycharmProjects/untitled2/Test/inplicitreference.py", line 13, in <module>
    room.displaymeasurement("depth")
  File "/home/townsend/Documents/PycharmProjects/untitled2/Test/inplicitreference.py", line 8, in displaymeasurement
    print(self.side)
AttributeError: 'shape' object has no attribute 'side'

What syntax am I missing to communicate to the computer to replace side with the entered argument depth and process from there.

I have spent a couple of days searching but I can't seem to find an attempt at a similar construction. Perhaps it's because I'm using incorrect terminology. I am very new to this.

I don't expect this method to work but I thought it was the best way to illustrate. I have tried several different methods.

I am aware of a series of if checks as a solution but I'm convinced there's an simpler and more expandable solution.

def displaymeasurement(self, side):
    if side == "length":
        print(self.length)
    if side == "bredth":
        print(self.bredth)
    if side == "depth":
        print(self.depth)
Chris Martin
  • 30,334
  • 10
  • 78
  • 137

2 Answers2

0

This is a fragile way to search for member's in an object's look up table. getattr() is intended for just this use case. Example below:

class MyClass(object):
    def __init__(self):
        self.x = 'foo'
        self.y = 'bar'

myClass = MyClass()

try:
    print(getattr(myClass, 'x'))
    print(getattr(myClass, 'y'))
    print(getattr(myClass, 'z'))

except AttributeError:
    print 'Attribute not found.'

Sample Output:

foo
bar
Attribute not found.
ospahiu
  • 3,465
  • 2
  • 13
  • 24
0

You need to use the getattr builtin method. This allows you to search for an attribute of a class with a string.

class Room:
    def __init__(self, length, bredth, depth):
        self.length = length
        self.bredth = bredth
        self.depth = depth

    def displaymeasurement(self, side):
        print(getattr(self, side))


kitchen = Room(10, 20, 15)

kitchen.displaymeasurement("depth")