相关疑难解决方法(0)

为什么我不能在Python中扩展bool?

>>> class BOOL(bool):
...     print "why?"
... 
why?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    type 'bool' is not an acceptable base type
Run Code Online (Sandbox Code Playgroud)

我以为Python信任程序员.

python boolean restriction

26
推荐指数
4
解决办法
5476
查看次数

python如何阻止类被子类化?

我在python文档中遇到了以下内容:

布尔([X])

使用标准真值测试程序将值转换为布尔值.如果x为false或省略,则返回False; 否则返回True.bool也是一个类,它是int的子类.类bool不能进一步子类化.它唯一的例子是假和真.

我从来没有想过要进行子类化bool,但很自然地我立即尝试了它,果然:

>>> class Bool(bool):
    pass

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    class Bool(bool):
TypeError: Error when calling the metaclass bases
    type 'bool' is not an acceptable base type
Run Code Online (Sandbox Code Playgroud)

所以,问题是:这是怎么做到的?我可以应用相同的技术(或不同的技术)来标记我自己的类final,即保持它们不被子类化吗?

python final subclass

11
推荐指数
1
解决办法
2140
查看次数

标签 统计

python ×2

boolean ×1

final ×1

restriction ×1

subclass ×1