访问类使用Python中的变量属性? [英] Access to class attributes by using a variable in Python?

查看:206
本文介绍了访问类使用Python中的变量属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP我可以像这样访问类属性:

 < PHP //很简单:)
类识别TestClass {}
$ TC =新识别TestClass {};
$属性='富';
$ TC-GT&{$属性} ='吧';
回声TC-$>富
//应该呼应'酒吧'

我怎么能在Python这样做吗?

 类识别TestClass()
TC =识别TestClass
属性='富'
#这里来的魔力?
打印tc.foo
#应该呼应'酒吧'


解决方案

这个问题已经被问了好几次。您可以使用 GETATTR 通过名称来获得属性:

 打印GETATTR(TC,'富')

这适用于方法以及

  GETATTR(TC,方法名)(ARG1,ARG2)

要设置按名称使用 SETATTR

属性

  SETATTR(TC,'富','棒')

要检查一个属性存在使用 hasattr

  hasattr(TC,'富')

In PHP I can access class attributes like this:

<?php // very simple :)
class TestClass {}
$tc = new TestClass{};
$attribute = 'foo';
$tc->{$attribute} = 'bar';
echo $tc->foo
// should echo 'bar'

How can I do this in Python?

class TestClass()
tc = TestClass
attribute = 'foo'
# here comes the magic?
print tc.foo
# should echo 'bar'

解决方案

This question has been asked several times. You can use getattr to get the attribute by name:

print getattr(tc, 'foo')

This works for methods as well:

getattr(tc, 'methodname')(arg1, arg2)

To set an attribute by name use setattr

setattr(tc, 'foo', 'bar')

To check if an attribute exists use hasattr

hasattr(tc, 'foo')

这篇关于访问类使用Python中的变量属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆