Динамическое наследование и атрибуты Python - PullRequest
0 голосов
/ 05 февраля 2019

Я ищу решение, которое позволило бы мне иметь динамическое наследование классов на основе определенных условий (Python 3.6).Это кажется достаточно простым, но я не могу получить атрибуты родительских классов, которые будут доступны в дочернем классе.Все, что зависит от self, либо выдает ошибку отсутствующего аргумента, либо атрибут не появляется.Я реализовал решения проблемы, приведенные здесь и здесь для динамического наследования, но все же столкнулся с той же проблемой с атрибутами дочернего класса.

Для примера:

class Parent:
    def __init__(self):
        self.some_value = 1

    def some_function(self):
        return self.some_value

def classFactory(parent):
    class child(parent):
        def __init__(self, parent):
            super(child, self).__init__()
            parent.__init__(self)
            self.some_other_value = 2

        def some_other_function(self):
            return self.some_value + self.some_other_value
    return child

child_class = classFactory(Parent)

child_class.some_value
AttributeError: type object 'child' has no attribute 'some_value'

child_class.some_other_value
AttributeError: type object 'child' has no attribute 'some_other_value'

child_class.some_other_function()
TypeError: some_other_function() missing 1 required positional argument: 'self'

Однако, если я возьму ту же самую конструкцию child и удалю ее из определения функции, она будет работать.

class child(Parent):
    def __init__(self, parent):
        super(child, self).__init__()
        parent.__init__(self)
        self.some_other_value = 2

    def some_other_function(self):
        return self.some_value + self.some_other_value

child_class = child(Parent)
print(child_class.some_value)
# 1
print(child_class.some_other_value)
# 2
print(child_class.some_other_function())
# 3

Почему атрибуты не являютсянаследуется в первом случае, но во втором?Как я могу написать динамическое наследование, чтобы дать мне ожидаемое поведение (как показано во втором случае)?

1 Ответ

0 голосов
/ 05 февраля 2019

Это работает, если я создаю экземпляр дочернего класса с родительским аргументом в return child(parent).Это сохраняет атрибуты и методы как родительского, так и дочернего.

class Parent:
    def __init__(self):
        self.some_value = 1

    def some_function(self):
        return self.some_value

def classFactory(parent):
    class child(parent):
        def __init__(self, parent):
            parent.__init__(self)
            self.some_other_value = 2

        def some_other_function(self):
            return self.some_value + self.some_other_value
    return child(parent)

child_class = classFactory(Parent)

print(child_class.some_value)
# 1
print(child_class.some_other_value)
# 2    
print(child_class.some_other_function())
# 3
print(child_class.some_function())
# 1
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...