gpt4 book ai didi

python - 确定给定的类属性是否为属性,Python 对象

转载 作者:IT老高 更新时间:2023-10-28 22:08:21 27 4
gpt4 key购买 nike

这一切都在标题中。下面是一个例子:

class A(object):
my_var = 5

def my_method(self, drink='beer'):
return 'I like %s' % drink

@property
def my_property(self):
return 'I do not drink coffee'

我实例化了一个 A 对象,我想知道每个属性的类型以及它是否是可调用的。为此,我使用 dir().

obj = A()

for attr in dir(obj):
print 'Type: %s' % type(obj)
print 'Is callable: %s' % callable(attr)

我还必须知道属性是否是属性。我确信有办法知道这一点。我们将不胜感激所有建议。

最佳答案

您需要查看类(通常是描述符的情况),对于您可以通过 __class__ 属性或使用 type 函数找到的对象:

>>> obj.__class__.my_property
<property object at 0xb74bd16c>

或通过

>>> type(obj).my_property
<property object at 0xb720b93c>

这些会产生相同的“属性对象”,就像您要直接检查类的属性一样(意味着您知道代码中的类名称,而不是像您应该做的那样动态检查它):

>>> A.my_property
<property object at 0xb7312345>

所以要测试一个对象的特定属性是否是一个属性,这将是一种解决方案:

>>> isinstance(type(obj).my_property, property)
True

关于python - 确定给定的类属性是否为属性,Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17735520/

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