![](/img/trans.png)
[英]Is it possible to access instance attributes separately in a class in 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
方法的最佳方法是什么? 我將對所有屬性運行相同的檢查。
最簡單的方法是不要將它們存儲為單獨的屬性。 在此示例中,我使用參數打包將a
, b
和c
作為元組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.