检查自我.__ class__的目的是什么? - 蟒蛇 [英] What is the purpose of checking self.__class__ ? - python

查看:136
本文介绍了检查自我.__ class__的目的是什么? - 蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查 self .__ class __ 的目的是什么?我找到了一些创建抽象接口类的代码,然后检查它的 self .__ class __ 是否本身,例如

What is the purpose of checking self.__class__ ? I've found some code that creates an abstract interface class and then checks whether its self.__class__ is itself, e.g.

class abstract1 (object):
  def __init__(self):
    if self.__class__ == abstract1: 
      raise NotImplementedError("Interfaces can't be instantiated")

目的是什么?
是否检查该类是否属于自己类型?

代码来自NLTK的 http://nltk.googlecode.com/svn/trunk/doc/api/nltk。 probability-pysrc.html#ProbDistI

推荐答案

self .__ class __ 是对当前实例的类型的引用。

self.__class__ is a reference to the type of the current instance.

对于 abstract1的实例,那就是 abstract1 class 本身,这是你不想要的抽象类。抽象类仅用于子类,而不是直接创建实例:

For instances of abstract1, that'd be the abstract1 class itself, which is what you don't want with an abstract class. Abstract classes are only meant to be subclassed, not to create instances directly:

>>> abstract1()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NotImplementedError: Interfaces can't be instantiated

对于子类的实例 abstract1 self .__ class __ 将是对特定子类的引用:

For an instance of a subclass of abstract1, self.__class__ would be a reference to the specific subclass:

>>> class Foo(abstract1): pass
... 
>>> f = Foo()
>>> f.__class__
<class '__main__.Foo'>
>>> f.__class__ is Foo
True

这里抛出异常就像使用断言语句中的其他语句,它可以防止你犯下愚蠢的错误。

Throwing an exception here is like using an assert statement elsewhere in your code, it protects you from making silly mistakes.

注意 pythonic 测试实例类型的方法是使用 type() function ,以及身份测试,运算符:

Note that the pythonic way to test for the type of an instance is to use the type() function instead, together with an identity test with the is operator:

class abstract1(object):
    def __init__(self):
        if type(self) is abstract1: 
            raise NotImplementedError("Interfaces can't be instantiated")

没什么意义在这里使用相等测试和自定义类一样, __ eq __ 基本上都是作为身份测试实现的。

There is little point in using an equality test here as for custom classes, __eq__ is basically implemented as an identity test anyway.

Python还包括一个标准库来定义抽象基类,称为 abc 。它允许您将方法和属性标记为抽象,并拒绝创建尚未重新定义这些名称的任何子类的实例。

Python also includes a standard library to define abstract base classes, called abc. It lets you mark methods and properties as abstract and will refuse to create instances of any subclass that has not yet re-defined those names.

这篇关于检查自我.__ class__的目的是什么? - 蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆