[Python] How to enforce a child class to set attributes using abstractproperty decorator in...

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I want to enforce a Child class to set several attributes(instance variables), to achieve I am using abstractproperty decorator in python 2.7. Here is the sample code:

    from abc import ABCMeta, abstractproperty
    class Parent(object):
    __metaclass__ = ABCMeta
    @abstractproperty
    def name(self):
    pass

    class Child1(Parent):
    pass

    class Child2(Parent):
    name = 'test'

    class Child3(Parent):
    def __init__(self):
    self.name = 'test'

    obj_child1 = Child1()


    Child1 object creation gives an error as expected.

    obj_child2 = Child2()


    Child2 object creation works fine as because abstract attribute 'name' is set

    However

    obj_child3 = Child3()


    gives TypeError: Can't instantiate abstract class Child3 with abstract methods name

    I did not understand:although the attribute 'name' is set in the init method, why the Child3 object creation is throwing type error.

    My requirement is set attributes inside a method of child class. An explanation of what is wrong with child2 class and if there is a better way to enforce a child class to set attributes in a method will help me. Thanks in advance.

    Continue reading...

Compartilhe esta Página