Python: deleting a class attribute in a subclass

后端 未结 7 821
野性不改
野性不改 2020-12-25 11:22

I have a subclass and I want it to not include a class attribute that\'s present on the base class.

I tried this, but it doesn\'t work:

>         


        
7条回答
  •  梦谈多话
    2020-12-25 11:40

    You can use delattr(class, field_name) to remove it from the class definition.

    Full example:

    # python 3
    class A:  
        def __init__(self):
            self.field_to_keep = "keep this in B"
            self.field_to_delete = "don't want this in B"
    
    class B(A):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            delattr(self, 'field_to_delete')
    

提交回复
热议问题