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

Two versions of self object within class, how can this be?

我一直在试验 class,其中包含返回生成的 class 的函数。

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

当将 'own' 分配给 'self' 时,python 创建了自己的第二个版本并赋予它不同的 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 不同,我怎么只能有一个?

我认为您需要将 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}