python - 从不可变类型继承

标签 python string list inheritance int

<分区>

我想知道 intliststring 和其他不可变类型的继承是如何工作的。

基本上我会像这样继承一个类:

class MyInt(int):
    def __init__(self, value):
        ?!?!?

我似乎无法弄清楚,如何设置像为 int 设置的值?如果我执行 self.value = value 那么我的类将像这样使用:

mi = MyInt(5)
print(mi.value) # prints 5

而我想这样使用它:

mi = MyInt(5)
print(mi) # prints 5

我该怎么做?

最佳答案

您可以子类化 int,但因为它是不可变的,所以您需要提供 .__new__() constructor hook :

class MyInt(int):
    def __new__(cls, value):
        new_myint = super(MyInt, cls).__new__(cls, value)
        return new_myint

您确实需要调用基础 __new__ 构造函数来正确创建您的子类。

在 Python 3 中,您可以完全省略 super() 的参数:

class MyInt(int):
    def __new__(cls, value):
        new_myint = super().__new__(cls, value)
        return new_myint

当然,这假设你想在传递给 super().__new__() 之前操纵 value 或者再操纵 new_myint返回前;否则,您也可以删除整个 __new__ 方法,并将其实现为 class MyInt(int): pass

关于python - 从不可变类型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15085917/

相关文章:

Java Regex - 匹配不在字符串内的行单词

c++ - 将 Strncmp 与文件中的字符串一起使用

c++ - 如何从字符串中获取词 vector ?

c# - 用于 IEnumerable 列表的聚合方法

python - 针对不同的 Bazel 规则使用不同的 python 版本的方法

python 记录 : email entire log file as attachment when level >= ERROR

python - 有效地计算小于给定值的列表条目

python - 在python中打印两个不同列表的相同索引

python - Flask 中的 (pymysql.err.IntegrityError) (1451, 'Cannot delete or update a parent row: a foreign key constraint fails...')

python - 取 Pandas Column 的前 6 位数字