[英]What's the best way to check if class instance variable is set in Python?
I have a variable which may or may not get a value in the instance:我有一个变量,它可能会或可能不会在实例中获得值:
class EC():
__init__(self, a=False):
...
if a: self.__var = ...
Later I want to check if the __var exists in the instance.后来我想检查__var 是否存在于实例中。 Because prepending __ to the name changes the internal name to _EC__var the checking code becomes a little bit messy:
因为在名称前面加上__会将内部名称更改为_EC__var,所以检查代码变得有点混乱:
if ''.join(['_',self.__class__.__name__,'__name']) in self.__dict__: ...
Is code above considered normal or not?上面的代码是否被认为是正常的? If not what are the preferred alternatives?
如果不是,首选的替代方案是什么?
One option I can think of is to give __var some value anyway, for example:我能想到的一种选择是无论如何给__var一些值,例如:
_no_value = object()
...
def __init__(self, a):
self.__var = _no_value
...
if a: self.__var = ...
So later I can compare __var to _no_value instead of a mess with internal variables.所以稍后我可以将__var与_no_value进行比较,而不是将内部变量弄得一团糟。
You've forgotten the EAFP principle :你忘记了EAFP 原则:
try:
value = self.__var
except AttributeError:
# do something else
If you're determined to use a sentinel, you can combine it with a class variable:如果您决定使用哨兵,则可以将其与类变量结合使用:
class EC():
__var = object():
...
if self.__var is not EC.__var:
...
Just use hasattr(self, '_var') to see if it exists - it may be set to None but it will exist if hasattr says it does.只需使用 hasattr(self, '_var') 来查看它是否存在——它可能被设置为 None 但如果 hasattr 说它存在,它就会存在。
Eg:例如:
>>> 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
>>>
Just set it to None
on the class :只需在课堂上将其设置为
None
:
class EC():
__var = None
__init__(self, a=False):
...
if a: self.__var = ...
then test for if self.__var is not None
.然后测试
if self.__var is not None
。
If None
should be a valid value for the attribute, use a different singleton sentinel:如果
None
应该是属性的有效值,请使用不同的单例标记:
_sentinel = object()
class EC():
__var = _sentinel
__init__(self, a=False):
...
if a: self.__var = ...
and test for if self.__var is not _sentinel
.并测试
if self.__var is not _sentinel
。
This way, all references to __var
are properly rewritten to include the class name.这样,对
__var
所有引用都被正确重写以包含类名。
The other path would be to not use double-underscore names for your attributes.另一种方法是不要为您的属性使用双下划线名称。
__var
should only be used for attributes you want to namespace to your specific class so that subclasses do not accidentally clobber it with their own attributes. __var
应该只用于您希望命名空间到特定类的属性,以便子类不会意外地用自己的属性破坏它。
In other words, do not use double-underscore names unless you really understand what they are for and actually need it.换句话说,不要使用双下划线名称,除非您真的了解它们的用途并且确实需要它。 Any code that is not part of a framework for wider consumption by unknown third parties?
任何不属于未知第三方更广泛使用的框架的一部分的代码? Just stick to single underscores instead.
只需坚持使用单个下划线。
I guess there is a simple way to check this out.我想有一个简单的方法来检查这个。 This is the way I tried it.
这是我试过的方法。
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)
Now instantiate the above class:现在实例化上面的类:
t = Test('123', 'asd', True)
The above code outputs something like:上面的代码输出如下:
The variable exists
If you want to see the contents of self.__dict__
.如果你想查看
self.__dict__
的内容。 Just type: print(self.__dict__)
The output of above code will be like:只需键入:
print(self.__dict__)
上面代码的输出将如下所示:
{'a': '123', 'b': 'asd', 'c': True, 'd': 'The variable exists'}
All the instance variables are stored in the format of dictionary in self.所有的实例变量都以字典的形式存储在self. dict
字典
I tried this out in python 3.8.1 and python 2.6.6.我在 python 3.8.1 和 python 2.6.6 中尝试了这个。 It worked out.
它成功了。 If there is any misconception with the answer, please report back by comment.
如果对答案有任何误解,请通过评论反馈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.