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

标签 python python-3.x loops getter

我知道如何迭代对象的属性。但这不包括通过 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/

相关文章:

c++ - C++ 中的 Python struct.pack/unpack 等价物

python - 如何计算一个数字与均值的标准差是多少?

python - 如何使用正则表达式删除制表符和换行符

python 3 : class "template" (function that returns a parameterized class)

PHP循环curl请求一个一个

python - 使用 python3(linux) 设置 selenium 时遇到问题

python - Pandas 。如何从 ZIP 存档中读取 Excel 文件

python - 如何迭代多个文本文件中的行并提取表中的值。

PHP循环创建Javascript

c# - 从循环中启动线程并传递循环 ID