1

I have already figured out the answer to that, so I am placing it here as a question to myself - for the sake of those that may come up with similar question.

Basically, I wanted to be able to delete an object method. The reason?

I have an action that has to be executed once per object life. This action cannot be placed in the __init__ method since I need system fully initialized before it is performed.

I have a suitable place holder for that action - a method existing in the parent class. But I would like to be able to avoid checking the condition every time the method is called by framework.

So I tried this approach:

In [193]: class Parent(object): def place_for_action(self): print 'This is parent' .....: In [194]: class Child(Parent): def place_for_action(self): super(Child, self).place_for_action() print 'This is child' delattr(self, 'place_for_action') .....: 

When I tried it, I failed

In [186]: c= Child() In [187]: c.place_for_action() This is child --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /homes/markg/<ipython-input-187-da53ac96ffa9> in <module>() ----> 1 c.place_for_action() /homes/markg/<ipython-input-185-7037db53bd87> in do_once(self) 2 def place_for_action(self): 3 print 'This is child' ----> 4 delattr(self, 'place_for_action') 5 AttributeError: 'Child' object attribute 'place_for_action' is read-only 
5
  • What? Why can't you do it at the end of __init__? What other instantiation is required? Commented Sep 18, 2014 at 13:36
  • @jonrsharpe It is a complex graphical implementation. The action is to send signals to other components of the system, and there's no guarantee that the components are initialized at the time Commented Sep 18, 2014 at 13:39
  • I'm dubious that this is necessary, but it's hard to tell without seeing more of your actual code. Commented Sep 18, 2014 at 13:58
  • @chepner, there's such a thing as "existing design constraint". Do you have a better answer to the question? I will be happy to see it. Commented Sep 18, 2014 at 14:28
  • I don't because I don't know what your design constraints are, hence my comment rather than an actual answer. Commented Sep 18, 2014 at 14:30

1 Answer 1

4

OK, the answer was - delete method at the class level - which suits my need

In [195]: class Child(Parent): def place_for_action(self): super(Child, self).place_for_action() print 'This is child' delattr(self.__class__, 'place_for_action') .....: 

Works like charm

In [196]: c = Child() In [197]: c.place_for_action() This is parent This is child In [198]: c.place_for_action() This is parent 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.