Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: deleting a class attribute in a subclass

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:

>>> class A(object): ...     x = 5 >>> class B(A): ...     del x Traceback (most recent call last):   File "<pyshell#1>", line 1, in <module>     class B(A):   File "<pyshell#1>", line 2, in B     del x NameError: name 'x' is not defined 

How can I do this?

like image 945
Ram Rachum Avatar asked May 19 '11 10:05

Ram Rachum


People also ask

How do you delete a class variable in Python?

Python's del statement is used to delete variables and objects in the Python program. Iterable objects such as user-defined objects, lists, set, tuple, dictionary, variables defined by the user, etc. can be deleted from existence and from the memory locations in Python using the del statement.

How do you delete an attribute in Python?

The delattr() method is used to delete the named attribute from the object, with the prior permission of the object. Syntax: delattr(object, name) The function takes only two parameter: object : from which the name attribute is to be removed. name : of the attribute which is to be removed.

How do I remove a value from an object in Python?

The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.

How do you delete an object in Python?

The del keyword in python is primarily used to delete objects in Python. Since everything in python represents an object in one way or another, The del keyword can also be used to delete a list, slice a list, delete a dictionaries, remove key-value pairs from a dictionary, delete variables, etc.


2 Answers

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

like image 173
Bhushan Avatar answered Sep 20 '22 07:09

Bhushan


You don't need to delete it. Just override it.

class B(A):    x = None 

or simply don't reference it.

Or consider a different design (instance attribute?).

like image 40
Keith Avatar answered Sep 21 '22 07:09

Keith