Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在分配整数时将其替换为其他类_Python - Fatal编程技术网

Python 如何在分配整数时将其替换为其他类

Python 如何在分配整数时将其替换为其他类,python,Python,我有一个名为newInteger的类和一个名为num的变量,但我希望num是newInteger()而不是int()。代码如下 class newInteger(int): def __init__(self, value): self.value = value num = 10 我希望行num=10的作用就像它是num=newInteger(10)一样。感谢所有能帮助我的人。我不确定这是否是你的意思,但如果你把这个类分配给一个变量。那么它将是该类的一个实例 例如:

我有一个名为newInteger的类和一个名为num的变量,但我希望num是newInteger()而不是int()。代码如下

class newInteger(int):
    def __init__(self, value):
        self.value = value

num = 10

我希望行
num=10
的作用就像它是
num=newInteger(10)
一样。感谢所有能帮助我的人。

我不确定这是否是你的意思,但如果你把这个类分配给一个变量。那么它将是该类的一个实例

例如:

class newInteger(int):
    def __init__(self, value):
        self.value = value

num = 10

if num == 10:
    num = newInteger(10)
印刷品:
hello

您可以运行一个与主程序并行的小线程,将所有创建的整数替换为
newInteger

import threading
import time

class newInteger(int):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return "newInteger " + str(self.value)

def replace_int():
    while True:
        g = list(globals().items())
        for n, v in g:
            if type(v) == int:
                globals()[n] = newInteger(v)

threading.Thread(target=replace_int, daemon=True).start()
num = 10
time.sleep(1)
print(num)

但这是非音速的,而且很难调试。您应该只使用显式转换

,这还不是很好,不过还是要感谢您的尝试。基本上,我希望在编写num=10时运行num=newInteger(10)行。Megalng的答案是正确的。谢谢你的帮助。你可以做
num=newInteger(10)
num
成为类实例。你能解释一下你期望的是什么吗?你能解释一下用例吗?用一个示例用例来回答可能更容易。感谢堆的回答,它真的很有帮助。