python用于类属性的循环?

python For loop for class attributes?

如果一个类中的参数不等于none,有没有方法可以循环一个函数?我知道如何使用大量的if循环来实现这一点,但是是否还有其他方法可以做到这一点?

下面是我想做的一个例子:

1
2
3
4
5
6
7
8
class Name:
    def __init__(self,name,favfood,favcolour,favsport):
        self.name = name
        self.favfood = favfood
        self.favcolour = favcolour
        self.favsport = favsport

henry = Name("Henry","Sushi","Blue",None)

我想要一个能打印出他最喜欢的东西的函数,但是如果没有的话会跳过它,这对于类来说是一个for循环。

对于类中的每个属性都有一个forloop方法吗?


可以使用self对象的__dict__属性:

1
2
3
4
5
6
7
8
9
10
11
class Name:
    def __init__(self,name,favfood,favcolour,favsport):
        self.name = name
        self.favfood = favfood
        self.favcolour = favcolour
        self.favsport = favsport
        for key, value in self.__dict__.items():
            if value is not None:
                print('%s: %s' % (key, value))

henry = Name("Henry","Sushi","Blue",None)

此输出:

1
2
3
name: Henry
favfood: Sushi
favcolour: Blue


*更新后将使用__dict__属性,如@blhsing建议的那样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Name:
    def __init__(self,name,favfood,favcolour,favsport):
        self.name = name
        self.favfood = favfood
        self.favcolour = favcolour
        self.favsport = favsport

    def print_favs(self):
        '''even better using @blh method'''
        [print(f'{k}: {v}') for k, v in self.__dict__.items() if v != None]



henry = Name("Henry","Sushi","Blue",None)
henry.print_favs()
1
2
3
4
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 helping.py
name: Henry
favfood: Sushi
favcolour: Blue