簡體   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