[BangPypers] how to delete base class attribute

steve steve at lonetwin.net
Thu Jul 29 12:09:01 CEST 2010


Hi Nitin,

On 07/29/2010 02:18 PM, Nitin Kumar wrote:
> Hi all,
>
>
>
> Say I have 10 functions in base class and I have inherited it in some
> derived class.
>
> But I only want 9 of the base class function to be available in child class.
> (and I don’t want to make that one class private)
>
>

Python encourages clear design by not providing facilities to /enforce/ policies 
as part of the language. That's the reason why there are no 
public/protected/private keywords in python. There are only conventions to be 
followed. Here are some possible solutions:

a. Are you sure you got your class hierarchy right ? If one class needs all the 
methods of the other except one, the one with the most commonality should 
probably be the base class. In your case, it would be flipping the hierarchy on 
it' head.

b. If some method is 'special' to a class name it using leading and trailing 
'__' so that users deriving from the class know it is special.

c. This is now going into hacky territory -- if you decide to keep the same 
hierarchy as you have now, assign self.A in class 'y' to None[1] or explicitly 
implement it to raise an AttributeError[2]. The reason you cannot 'del' self.A 
is precisely because of what the error says "AttributeError: y instance has no 
attribute 'A'" -- A is just a 'bound' method to the object, not an attribute of 
the object and AFAICT there is no way to un-bind something off an object.


[1]

class y(x):
     def __init__(self):
         super(y, self).__init__() # btw, use super if possible
         self.A = None

[2]
class y(x):
     def __init__(self):
     ...
     def A(self):
         raise AttributeError("y instance has no attribute A")

hth,
cheers,
- steve

-- 
random spiel: http://lonetwin.net/
what i'm stumbling into: http://lonetwin.stumbleupon.com/


More information about the BangPypers mailing list