Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how can I dynamically remove a method from a class -- i.e. opposite of setattr

Tags:

python

setattr

I don't know if I have a good design here, but I have a class that is derived from unittest.TestCase and the way I have it set up, my code will dynamically inject a bunch of test_* methods into the class before invoking unittest to run through it. I use setattr for this. This has been working well, but now I have a situation in which I want to remove the methods I previously injected and inject a new set of methods. How can I remove all the methods in a class whose names match the pattern test_*?

like image 708
tadasajon Avatar asked May 22 '13 20:05

tadasajon


People also ask

What is __ add __ in Python?

The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1.

What is __ new __ in Python?

In the base class object , the __new__ method is defined as a static method which requires to pass a parameter cls . cls represents the class that is needed to be instantiated, and the compiler automatically provides this parameter at the time of instantiation.

What is dynamic method in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

What is __ INT __ in Python?

The __int__ method is called to implement the built-in int function. The __index__ method implements type conversion to an int when the object is used in a slice expression and the built-in hex , oct , and bin functions.


2 Answers

It's called delattr and is documented here.

like image 77
BrenBarn Avatar answered Sep 22 '22 00:09

BrenBarn


>>> class Foo:
    def func(self):
        pass
...     
>>> dir(Foo)
['__doc__', '__module__', 'func']
>>> del Foo.func
>>> dir(Foo)
['__doc__', '__module__']
like image 21
Ashwini Chaudhary Avatar answered Sep 23 '22 00:09

Ashwini Chaudhary