gpt4 book ai didi

python - 如何迭代由 getter 或 @property 定义的对象的属性?

转载 作者:太空宇宙 更新时间:2023-11-03 21:06:33 25 4
gpt4 key购买 nike

我知道如何迭代对象的属性。但这不包括通过 getter/setter 或 @property 装饰器实现的属性。

我如何迭代这些?

class MyClass:

def __init__(self):
self.foo = "bar"

@property
def myprop(self):
return "hello"


my_instance = MyClass()

for i in my_instance.__dict__:
print("object has attribute %s" % i)

这个小脚本打印:

object has attribute foo

我想要的是一个打印的脚本:

object has attribute foo
object has attribute myprop

最佳答案

您可以使用dir()来获取所有属性,尽管这将包括从基类继承的方法,包括来自对象的所有dunder方法:

class MyClass:

def __init__(self):
self.foo = "bar"

@property
def myprop(self):
return "hello"


my_instance = MyClass()

for i in dir(my_instance):
print("object has attribute %s" % i)

打印:

object has attribute __class__
object has attribute __delattr__
object has attribute __dict__
object has attribute __dir__
object has attribute __doc__
object has attribute __eq__
object has attribute __format__
object has attribute __ge__
object has attribute __getattribute__
object has attribute __gt__
object has attribute __hash__
object has attribute __init__
object has attribute __init_subclass__
object has attribute __le__
object has attribute __lt__
object has attribute __module__
object has attribute __ne__
object has attribute __new__
object has attribute __reduce__
object has attribute __reduce_ex__
object has attribute __repr__
object has attribute __setattr__
object has attribute __sizeof__
object has attribute __str__
object has attribute __subclasshook__
object has attribute __weakref__
object has attribute foo
object has attribute myprop

您可以使用字符串操作排除一些:

for i in dir(my_instance):
if i.startswith("__"):
continue
print("object has attribute %s" % i)

打印:

object has attribute foo
object has attribute myprop

关于python - 如何迭代由 getter 或 @property 定义的对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55357018/

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