简体   繁体   English

检查类实例变量是否在 Python 中设置的最佳方法是什么?

[英]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.

相关问题 子类化 Python 集合类、添加新实例变量的正确(或最佳)方法是什么? - What is the correct (or best) way to subclass the Python set class, adding a new instance variable? 在 Python 中,避免对 __init__ 参数和实例变量使用相同名称的最佳方法是什么? - In Python, what's the best way to avoid using the same name for a __init__ argument and an instance variable? Python:从 class 实例中访问变量的最佳方式? - Python: Best way to access variable from within a class instance? 检查部分(类)是否是类的实例的最佳方法 - Best way to check if a partial(Class) is an instance of Class 在Python中检查变量是否为数字类型的最佳方法是什么 - What is the best way to check if a variable is of numeric type in python 使用python / GAE对cookie进行存在性检查的最佳方法是什么? - What's the best way to do an existence check on a cookie with python/GAE? 在 Python 中跳过迭代变量的 N 个值的最佳方法是什么? - What's the best way of skip N values of the iteration variable in Python? 在 Python 中创建对象时设置类属性的最佳方法是什么? - What is the best way to set the attributes of a class at object creation time in Python? 在Python中跟踪类实例变量的好方法是什么? - What's a good way to keep track of class instance variables in Python? 在 python 源文件中对类定义进行排序的最佳方法是什么? - What's the best way to sort class definitions in a python source file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM