类中有两个版本的self对象,这怎么可能?

时间:2019-03-21 10:52:02

标签: python class self

我一直在尝试一个包含返回所生成类的函数的类。

我希望生成的类具有“自我”对象。它获取了self中的所有属性,因此我将“ self”分配给生成的self变量,我将其命名为“ own”以减少混乱。

在将'own'分配给'self'时,python创建第二版的own并为其指定不同的ID。 调用该函数时,将返回旧的“ own”。

import copy
from pprint import pprint


class test_class1(object):
    def __init__(self, number):
        self.number=number
        self.abc=['a','b','c']

    def test_class2(self):
        class test_class(object):
            def __init__(own):
                print('own id:')
                pprint(id(own))
                print('own attributes:')
                pprint(own.__dict__)
                print('\n')

                own=copy.deepcopy(self)
                print('own has selfs attributes own.number:',own.number)
                print('own id:')
                pprint(id(own))
                print('own attributes:')
                pprint(own.__dict__)
                print('\n')

        return test_class

a=test_class1(7).test_class2()()
print('own has no attributes anymore')
print('own id:')
pprint(id(a))
print('own attributes:')
pprint(a.__dict__)
print('\n')

输出为:

own id:
140178274834248
own attributes:
{}


own has selfs attributes own.number: 7
own id:
140178274834584
own attributes:
{'abc': ['a', 'b', 'c'], 'number': 7}


own has no attributes anymore
own id:
140178274834248
own attributes:
{}

我找到了一种解决方法,但是有人可以解释为什么两个版本的“ own”具有不同的ID,以及我怎么只能拥有一个ID?

1 个答案:

答案 0 :(得分:0)

我认为您需要将own=copy.deepcopy(self)替换为own.__dict__.update(self.__dict__)。它不会更改id(own),但会将self的所有属性赋予复制的own对象。

代码:

import copy
from pprint import pprint


class test_class1(object):
    def __init__(self, number):
        self.number=number
        self.abc=['a','b','c']

    def test_class2(self):
        class test_class(object):
            def __init__(own):
                print('own id:')
                pprint(id(own))
                print('own attributes:')
                pprint(own.__dict__)
                print('\n')

                own.__dict__.update(self.__dict__)  # here is the change
                print('own has selfs attributes own.number:',own.number)
                print('own id:')
                pprint(id(own))
                print('own attributes:')
                pprint(own.__dict__)
                print('\n')

        return test_class

a=test_class1(7).test_class2()()
print('own still has attributes')
print('own id:')
pprint(id(a))
print('own attributes:')
pprint(a.__dict__)
print('\n')

输出:

own id:
140228632050376
own attributes:
{}


own has selfs attributes own.number: 7
own id:
140228632050376
own attributes:
{'abc': ['a', 'b', 'c'], 'number': 7}


own still has attributes
own id:
140228632050376
own attributes:
{'abc': ['a', 'b', 'c'], 'number': 7}