Home > Enterprise >  Delete an attribute of a parent class in a child class
Delete an attribute of a parent class in a child class

Time:01-11

How i can delete attribute of parent class in child class (not class instanse) in subclassing?

class Parent:
    attribute1 = 1
    attribute2 = 2


class Child(Parent):
    # need only attribute1


try:
    print(Child.attribute2)
except AttributeError:
    print("You deleted class attribute2")

How can I implement this?

I tried to use delattr(Child, "attribute2") or this method in child class:

    def __delattr__(self, item):
        object.__delattr__(self, item)

But this doesn't work. Maybe i need to use super() inside child class?

CodePudding user response:

I'm sorry, I confused you. I solved my problem in this way below, without attribute deleting.

class GrandParent:
    attribute1 = 1


class Parent(GrandParent):
    attribute2 = 2


class Child(GrandParent):
    # need only attribute1
    pass
  • Related