Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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中使用deepcopy创建实例?_Python_Python 3.x - Fatal编程技术网

如何在python中使用deepcopy创建实例?

如何在python中使用deepcopy创建实例?,python,python-3.x,Python,Python 3.x,我正在尝试继承Decimal并创建一个数学类来处理多态输入。我遇到的问题是,我所做的一切似乎都不允许我创建重复的实例 我已经看了几十个例子,但没有发现任何一个是从内部构造函数创建多个实例的。他们都是从外面做的 要使用多态输入重写数学函数,实例构造函数必须在类内部。没有别的办法。我已经用了十种不同的方法,查看了大量的在线文档(大部分都是大错特错的),希望这里有人能帮上忙 ### FOO.py import sys from decimal import Decimal, getcontext

我正在尝试继承Decimal并创建一个数学类来处理多态输入。我遇到的问题是,我所做的一切似乎都不允许我创建重复的实例

我已经看了几十个例子,但没有发现任何一个是从内部构造函数创建多个实例的。他们都是从外面做的

要使用多态输入重写数学函数,实例构造函数必须在类内部。没有别的办法。我已经用了十种不同的方法,查看了大量的在线文档(大部分都是大错特错的),希望这里有人能帮上忙

### FOO.py

import sys

from decimal import Decimal, getcontext
import socket
import operator
import re
import copy

class Amount(Decimal): 

    def __init__(self):  

        instancehex = hex(id(self)) 
        print ("class: ", self.__class__.__name__)
        print ("baseclass: ", self.__class__.__base__)
        print ("instance: ", instancehex)

        super(type(self),self).__init__() # inherit decimal for getcontext()

        print ("postinitclass: ", self.__class__.__name__)
        print ("postinitbaseclass: ", self.__class__.__base__)
        print ("postinitinstance: ", instancehex)

        # these are instance variables? If not, how from inside an instance-constructor? 

        self.value = Decimal(0.0) # our initial value
        self.isdefined = False # 

    def newamount(self, *arg): 

        # this should call __init__? Doesn't happen. 

        thisobject = copy.deepcopy(self)

        # these should be different memory addresses? 

        selfhex = hex(id(self)) 
        thishex = hex(id(thisobject))

        print ("\tself: ", str(selfhex))
        print ("\tcopy: ", str(thishex))

        if len(arg): 
            polyinput = arg[0]
            thisobject.setvalue(polyinput)
            self.isdefined = True

        return(thisobject)

    def setvalue(self,polyinput): 

        # polymorphic numeracy 

        print ("\t\tsetting from: ", polyinput.__class__.__name__)

        if polyinput.__class__.__name__ == "Amount": 
            self.value = (polyinput.value)
        elif polyinput.__class__.__name__ == "float": 
            self.value.from_float(polyinput)

    def __add__(self,polyinput):
        rcvamount = self.newamount(polyinput) 
        sumamount = self.newamount() 

        print ("ADDING:")

        if rcvamount.isdefined and self.isdefined: 
            print ("\tdefined values", str(self.value), ":", str(rcvamount.value))

            # super() is magical with operator intercepts? 

            sumamount.value = self.value + rcvamount.value 

        else: 
            assert False, "cannot add undefined values"

        return (sumamount)
# # #
类别:金额
基类:
实例:0x7f821c830ca8
后分类:金额
后基类:
启动后状态:0x7f821c830ca8
数量:
自我:0x7f821c830ca8
副本:0x7f821c830ca8
设置从:浮动
自我:0x7f821c830ca8
副本:0x7f821c830ca8
设置从:浮动
自我:0x7f821c830ca8
副本:0x7f821c830ca8
设置从:浮动
报告:金额0x7f821c830ca8 0
报告:金额0x7f821c830ca8 0
报告:金额0x7f821c830ca8 0
自我:0x7f821c830ca8
副本:0x7f821c830ca8
设置来源:金额
自我:0x7f821c830ca8
副本:0x7f821c830ca8
添加:
定义值0:0
金额0x7f821c830ca8 0
0 : 0
0 : 0 : 0

我相信你做得不对。您已经在
newamount
中有效地创建了
\uuuu init\uuuu
方法的副本。最好是将
Decimal
子类化,然后只重载要使用的方法

例如,如果另一个对象不是
Decimal
的实例,则可以创建一个方法来检查该对象的类型,并将其传递给
Amount
。然后,重载
\uuuuuuuuuuuuuuuuuuuu
\uuuuuuuu
方法允许
数量
对象接受多态添加

from collections.abc import Iterable
从十进制输入十进制
类别金额(十进制):
定义报告(自我):
返回“Amount({})”.format(self.\uuuu float\uuuu())
def_检查集(自身、其他):
如果isinstance(其他,十进制):
返回其他
如果存在(其他,可替换):
退货金额(其他[0])
退货金额(其他)
定义添加(自身、其他):
返回self.\uuuu类(super()。\uuuu添加(self.\u检查集(其他)))
定义(自身、其他):
返回自我+其他
a=金额(1.2)
a+4
#返回:
金额(1.599999999)
1+a
#返回:
金额(2.2)
#在代码中,iterables只接受第一个对象
a+[2,3,4]
#返回:
金额(3.2)

您可以定义一个
\uuuu deepcopy\uuu
方法来定制deepcopy如何与类一起工作。看一个例子,你能解释一下行吗:return“Amount({})”.format(self.\uuu float\uuuu())我以前从未见过这个表单。这是一种新的字符串格式迷你语言。这仍然不起作用。我无法在没有类型冲突的情况下将超类句柄引入属性,也无法设置getcontext().rounding或getcontext().prec,因为您描述的方法会导致双嵌套perens语法错误。因此,没有一个上下文可以在内部访问。使用上面的解决方案。所以它仍然是catch22.holdon。我可能已经修好了。天啊,我现在讨厌蟒蛇,我想它已经开始工作了。非常感谢!我至少重建了这个类十几次,让它工作了(我想)两次,然后其他东西需要调整,再次破坏它。我还是不明白。我只是不明白为什么我不能从类名称空间中调用构造函数,除非(显然)从匿名字符串对象中调用构造函数?
### testfoo.py 

import sys
from decimal import Decimal,getcontext

import socket
import operator
import re

import FOO

# set the class currency type

Factory = FOO.Amount()

print ("Amounts: ")
m0 = Factory.newamount(0.1) 
m1 = Factory.newamount(0.02) 
m2 = Factory.newamount(0.03) 

print ("REPORT: ",  m0.__class__, type(m0).__name__, hex(id(m0)), m0)
print ("REPORT: ", m1.__class__, type(m1).__name__, hex(id(m0)), m1)
print ("REPORT: ", m2.__class__, type(m2).__name__, hex(id(m0)), m2)

m3 = m2 + m1
print (type(m3).__name__, hex(id(m3)), m3)

print (m1,":", m2)
print (m1,":",m2,":",m3)
class:  Amount
baseclass:  <class 'decimal.Decimal'>
instance:  0x7f821c830ca8
postinitclass:  Amount
postinitbaseclass:  <class 'decimal.Decimal'>
postinitinstance:  0x7f821c830ca8
Amounts: 
    self:  0x7f821c830ca8
    copy:  0x7f821c830ca8
        setting from:  float
    self:  0x7f821c830ca8
    copy:  0x7f821c830ca8
        setting from:  float
    self:  0x7f821c830ca8
    copy:  0x7f821c830ca8
        setting from:  float
REPORT:  <class 'FOO.Amount'> Amount 0x7f821c830ca8 0
REPORT:  <class 'FOO.Amount'> Amount 0x7f821c830ca8 0
REPORT:  <class 'FOO.Amount'> Amount 0x7f821c830ca8 0
    self:  0x7f821c830ca8
    copy:  0x7f821c830ca8
        setting from:  Amount
    self:  0x7f821c830ca8
    copy:  0x7f821c830ca8
ADDING:
    defined values 0 : 0
Amount 0x7f821c830ca8 0
0 : 0
0 : 0 : 0