本文介绍了检查Python中的成员存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想检查一个对象是否有一个成员。一个例子就是在一个函数中创建一个单例。为此,您可以使用 hasattr

  class Foo (对象):
@classmethod
def singleton(self):
如果不是hasattr(self,'instance'):
self.instance = Foo()
return self.instance

但你也可以这样做:

  class Foo(object):
@classmethod
def singleton(self):
try:
return self.instance
除了AttributeError:
self.instance = Foo()
return self.instance

一种方法比另一种更好吗?



编辑添加了 @classmethod ...但请注意,问题是不是关于如何进行单例,但如何检查对象中成员的存在。



编辑:对于该示例,典型的用法是:

  s = Foo.singleton()

然后 s 是类型为 Foo 的对象,每次都相同。而且,通常这种方法被多次调用。

解决方案

这两种不同的方法:№1是LBYL le ap and and and creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates creates您测试之前的文件和您尝试自己创建的时间之间的文件?。这个论点在这里不适用,但这是一般的想法。例外情况不应被视为 例外。



在您的情况下,性能方面 - 设置异常管理器(尝试关键字)在创建异常($ code> raise 关键字和内部异常创建)时,CPython非常便宜是什么是相对昂贵的使用方法№2的例外只会提高一次;之后,您只需使用该资源。


I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr like this:

class Foo(object):
    @classmethod
    def singleton(self):
        if not hasattr(self, 'instance'):
            self.instance = Foo()
        return self.instance

But you can also do this:

class Foo(object):
    @classmethod
    def singleton(self):
        try:
            return self.instance
        except AttributeError:
            self.instance = Foo()
            return self.instance

Is one method better of the other?

Edit: Added the @classmethod ... But note that the question is not about how to make a singleton but how to check the presence of a member in an object.

Edit: For that example, a typical usage would be:

s = Foo.singleton()

Then s is an object of type Foo, the same each time. And, typically, the method is called many times.

解决方案

These are two different methodologies: №1 is LBYL (look before you leap) and №2 is EAFP (easier to ask forgiveness than permission).

Pythonistas typically suggest that EAFP is better, with arguments in style of "what if a process creates the file between the time you test for it and the time you try to create it yourself?". This argument does not apply here, but it's the general idea. Exceptions should not be treated as too exceptional.

Performance-wise in your case —since setting up exception managers (the try keyword) is very cheap in CPython while creating an exception (the raise keyword and internal exception creation) is what is relatively expensive— using method №2 the exception would be raised only once; afterwards, you just use the property.

这篇关于检查Python中的成员存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 04:43