gpt4 book ai didi

python - 使用变量调用类的属性

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:53 24 4
gpt4 key购买 nike

我对Python还是有点陌生​​,我正在尝试使用变量来调用类的特定属性。但是,我想我可能会错过一些东西。我在下面举了一个例子。感谢您的帮助!

 class character(object):
def __init__(self, name, name1, name2):
self.name = name
self.name1 = name1
self.name2= name2

bob = character('bob', 'bob1', 'bob2')


def print_name(var1, var2):
print(var1.var2)

print_name(bob, 'name1')

最佳答案

尝试使用getattr:

class character(object):
def __init__(self, name, name1, name2):
self.name = name
self.name1 = name1
self.name2= name2

bob = character('bob', 'bob1', 'bob2')


def print_name(var1, var2):
print(getattr(var1,var2))

print_name(bob, 'name1')

这来自documentation :

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

关于python - 使用变量调用类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47026332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com