繁体   English   中英

在python中访问类实例属性的最佳方法

[英]Best ways to access class instance attributes in python

我有一堂课,可以说:

#!/usr/bin/env python

class testclass(object):
    def __init__(self, a, b, c):
        self.__attr1 = a
        self.__attr2 = b
        self.__attr3 = c

    def meth(self):
        ## run some checks on self.__attr1, self.__attr2, self.__attr3 
                    ## How to do that?  

if __name__ == '__main__':
    t = testclass("dd", "ee", "gg")

问题:如果我有多个属性,而不仅仅是三个属性,那么编写meth方法的最佳方法是什么? 我将对所有属性运行相同的检查。

最简单的方法是不要将它们存储为单独的属性。 在此示例中,我使用参数打包将abc作为元组abc传递,并将其存储为self._attrs

class testclass(object):
    def __init__(self, *abc):
        self._attrs = abc

    def meth(self):
        for attr in self._attrs:
            print attr

if __name__ == '__main__':
    t = testclass("dd", "ee", "gg")

您对attr的检查不是很清楚

但我仍然认为

def get (自己,实例,所有者):

有什么可以帮助你的:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM