![](/img/trans.png)
[英]What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
[英]What's the best way to check if class instance variable is set in Python?
我有一个变量,它可能会或可能不会在实例中获得值:
class EC():
__init__(self, a=False):
...
if a: self.__var = ...
后来我想检查__var 是否存在于实例中。 因为在名称前面加上__会将内部名称更改为_EC__var,所以检查代码变得有点混乱:
if ''.join(['_',self.__class__.__name__,'__name']) in self.__dict__: ...
上面的代码是否被认为是正常的? 如果不是,首选的替代方案是什么?
我能想到的一种选择是无论如何给__var一些值,例如:
_no_value = object()
...
def __init__(self, a):
self.__var = _no_value
...
if a: self.__var = ...
所以稍后我可以将__var与_no_value进行比较,而不是将内部变量弄得一团糟。
你忘记了EAFP 原则:
try:
value = self.__var
except AttributeError:
# do something else
如果您决定使用哨兵,则可以将其与类变量结合使用:
class EC():
__var = object():
...
if self.__var is not EC.__var:
...
只需使用 hasattr(self, '_var') 来查看它是否存在——它可能被设置为 None 但如果 hasattr 说它存在,它就会存在。
例如:
>>> class a():
... def __init__(self):
... self.a = 3
... self._a_ = 4
... self.__a__ = 'Fred'
...
>>> A=a()
>>> hasattr(a, 'a')
False
>>> hasattr(A, 'a')
True
>>> hasattr(A, '_a_')
True
>>> hasattr(A, '__a__')
True
>>> hasattr(A, '__b__')
False
>>>
只需在课堂上将其设置为None
:
class EC():
__var = None
__init__(self, a=False):
...
if a: self.__var = ...
然后测试if self.__var is not None
。
如果None
应该是属性的有效值,请使用不同的单例标记:
_sentinel = object()
class EC():
__var = _sentinel
__init__(self, a=False):
...
if a: self.__var = ...
并测试if self.__var is not _sentinel
。
这样,对__var
所有引用都被正确重写以包含类名。
另一种方法是不要为您的属性使用双下划线名称。 __var
应该只用于您希望命名空间到特定类的属性,以便子类不会意外地用自己的属性破坏它。
换句话说,不要使用双下划线名称,除非您真的了解它们的用途并且确实需要它。 任何不属于未知第三方更广泛使用的框架的一部分的代码? 只需坚持使用单个下划线。
我想有一个简单的方法来检查这个。 这是我试过的方法。
class Test:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
if self.c:
self.d = "The variable exists"
if 'd' in self.__dict__:
print(self.d)
现在实例化上面的类:
t = Test('123', 'asd', True)
上面的代码输出如下:
The variable exists
如果你想查看self.__dict__
的内容。 只需键入: print(self.__dict__)
上面代码的输出将如下所示:
{'a': '123', 'b': 'asd', 'c': True, 'd': 'The variable exists'}
所有的实例变量都以字典的形式存储在self. 字典
我在 python 3.8.1 和 python 2.6.6 中尝试了这个。 它成功了。 如果对答案有任何误解,请通过评论反馈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.