Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 循环浏览属性列表_Python_List_Python 3.x_Properties - Fatal编程技术网

Python 循环浏览属性列表

Python 循环浏览属性列表,python,list,python-3.x,properties,Python,List,Python 3.x,Properties,我有以下问题。 我的类中有一个视图属性,可以访问配置,如果用户向配置中添加垃圾,则会引发ValueError 我想写一个方法来检查我的配置文件是否有错误,所以我想我会查看列表中的每个属性并尝试访问它的值。因此,我不需要为每个属性复制try except 我尝试了以下代码,当然,这些代码在创建列表时调用属性,因此在我的尝试之外抛出错误。 我的问题有一个优雅的解决方案吗 import random def load_config(): rand_number = random.randi

我有以下问题。 我的类中有一个视图属性,可以访问配置,如果用户向配置中添加垃圾,则会引发
ValueError

我想写一个方法来检查我的配置文件是否有错误,所以我想我会查看列表中的每个属性并尝试访问它的值。因此,我不需要为每个属性复制
try except

我尝试了以下代码,当然,这些代码在创建列表时调用属性,因此在我的尝试之外抛出错误。
我的问题有一个优雅的解决方案吗

import random


def load_config():
    rand_number = random.randint(0, 9)
    if rand_number == 5:
        raise ValueError

    return rand_number


class foo:
    @property
    def bar1(self):
        return load_config()

    @property
    def bar2(self):
        return load_config()

    @property
    def bar3(self):
        return load_config()

    @property
    def bar4(self):
        return load_config()

    @property
    def bar5(self):
        return load_config()


    def check_properties(self):
        properties = [
            self.bar1, //Exceptions are thrown here
            self.bar2,
            self.bar3,
            self.bar4,
            self.bar5,
        ]

        for property in properties:
            try:
                num = property
            except ValueError:
                print("ValueError at " + property.__name__)

my_foo = foo()
my_foo.check_properties()

要创建mve,我将属性体替换为对函数的调用,并创建一个随机的
ValueError

您可以使用以下内容定义
检查属性

def check_properties(self):
        properties = [property_name for property_name, obj in self.__class__.__dict__.items() 
                          if isinstance(obj, property)]

        for property_name in properties:
            try:
                getattr(self, property_name)
            except ValueError:
                print("ValueError at " + property_name)
它将尝试在
getattr
中计算属性

这不适用于基类继承的属性。如果使用继承,则可以使用如下帮助函数:

def get_property_names(cls, follow_inheritance=False):
    property_names = []

    for attr_name, attr in cls.__dict__.items():
        if isinstance(attr, property):
            property_names.append(attr_name)

    if follow_inheritance:
        for parent_class in cls.__mro__:
            if parent_class != cls:
                property_names.extend(get_property_names(parent_class, True))

    return property_names
然后将
检查属性定义为:

def check_properties(self):
        properties = get_property_names(self.__class__, follow_inheritance=True)

        for property_name in properties:
            try:
                getattr(self, property_name)
            except ValueError:
                print("ValueError at " + property_name)

您可以存储名称并使用
getattr(self,property\u name)
。@karthikr:这很正常。我认为你没有正确理解这个问题。@VincentSavard我怎样才能提取财产的名称?name似乎不适用于属性
num=getattr(self,“bar1”)
。等这就可以了。@Altoyr:您可以通过执行类似以下操作来获取所有属性名:
[property\u name for property\u name,obj in self.\uuu class\uuuuu.\uu dict\uuuuu.items(),如果存在(obj,property)]
。我会写一个答案。为了给其他通过此方法的人打个红旗,此解决方案是有风险的,因为它假设所有属性都应该被调用。如果有其他属性执行检查期间不希望执行的计算,则不要使用。它也不会检查类的父类,因此如果使用类继承,则必须更新它。@tdelaney:我假设人们知道风险,因为问题是“如何评估对象中的所有属性?”。不过你关于继承的观点是正确的。这一点绝对正确,在我的情况下效果很好,但在其他情况下可能会非常危险。