通过参数引用对象的属性

2024-10-03 17:16:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数,调用由传递的参数决定的属性

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")

这是我正在使用的代码的抽象,因为它太复杂了。我努力将它与所讨论的代码相匹配,它确实会产生相同的错误消息

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'

我缺少什么语法来与计算机通信以用输入的参数depth替换side并从那里进行处理

我花了几天时间寻找,但似乎找不到类似的建筑。也许是因为我用了不正确的术语。我对这个很陌生

我不指望这种方法能奏效,但我认为这是最好的说明方法。我试过几种不同的方法

我知道有一系列if检查可以作为解决方案,但我确信有一个更简单、更可扩展的解决方案

def displaymeasurement(self, side):
    if side == "length":
        print(self.length)
    if side == "bredth":
        print(self.bredth)
    if side == "depth":
        print(self.depth)

Tags: 方法代码selfhome参数ifdeflength
2条回答

这是一种在对象的查找表中搜索成员的脆弱方法^{}仅用于此用例。示例如下:

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.'

样本输出:

foo
bar
Attribute not found.

您需要使用getattr内置方法。这允许您搜索带有字符串的类的属性

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")

相关问题 更多 >