Как это может быть две версии объекта self внутри класса? - PullRequest
0 голосов
/ 21 марта 2019

Я экспериментировал с классом, содержащим функции, возвращающие сгенерированный класс.

Я хочу, чтобы сгенерированный класс имел объект self.Он получает все атрибуты внутри себя, поэтому я назначил «self» для сгенерированной переменной self, которую я назвал «own», чтобы уменьшить путаницу.

При назначении «own» python создает вторую версию own идает ему другой идентификатор.При вызове функции возвращается старое «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:
{}

Я нашел обходной путь, но кто-то может объяснить, почему существует две версии 'собственные »с разными идентификаторами и как я могу иметь только один?

1 Ответ

0 голосов
/ 21 марта 2019

Я думаю, вам нужно заменить 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}
...