Python继承自不可变类int,为什么参数'复印时订购事项?

时间:2016-07-12 03:02:19

标签: python inheritance int copy immutability

我正在尝试实现一个从int继承的类,并向其中添加一些成员,但是如果参数的顺序发生变化,我发现派生类中的实例无法正确复制(甚至是深层复制),请参阅下面的示例,尝试创建一个积极的int类:

# Example 1
import copy as cp
class PositiveInt(int): 
def __new__(cls, arg = 1, arg0 = 2, arg1 = 3):
    if arg < 0:
        arg = -arg
    return super(PositiveInt, cls).__new__(cls, arg)
def __init__(self, arg = 1, arg0 = 2, arg1 = 3):
    self.arg0 = arg0
    self.arg1 = arg1

n = PositiveInt(3, 4, 5)
m = cp.copy(n)
print(n, n.arg0, n.arg1)
print(m, m.arg0, m.arg1)

这将打印:
(3,4,5)
(3,4,5)

# Example 2
class PositiveInt(int):
def __new__(cls, arg0 = 2, arg = 1, arg1 = 3):
    if arg < 0:
        arg = -arg
    return super(PositiveInt, cls).__new__(cls, arg)
def __init__(self, arg0 = 2, arg = 1, arg1 = 3):
    self.arg0 = arg0
    self.arg1 = arg1

n = PositiveInt(4, 3, 5)
m = cp.copy(n)
print(n, n.arg0, n.arg1)
print(m, m.arg0, m.arg1)

这将打印:
(3,4,5)
(1,4,5)

唯一的区别是参数的顺序。在示例2中,复制将使用arg的默认值进行 new 中的实例化,但在示例1中不是这种情况。

1 个答案:

答案 0 :(得分:0)

m = cp.copy(n)最终致电m = PositiveInt(n),而m=PositiveInt(3)正在呼叫__copy__

你可以继承def __copy__(self): return PositiveInt(self.arg0,self,self.arg1)

__new__

或者你可以检查__copy__中的第一个参数(也许......我实际上不认为这会起作用)......但实际上你应该只是$group_id = explode(',',$session['group_id']); $this->db->select('*'); $this->db->where_in('group_id',$group_id); $this->db->get('notification');

的子类