[BangPypers] how to delete base class attribute

Jeffrey Jose jeffjosejeff at gmail.com
Sat Jul 31 20:24:44 CEST 2010


On Thu, Jul 29, 2010 at 6:34 PM, Anand Balachandran Pillai <
abpillai at gmail.com> wrote:

> On Thu, Jul 29, 2010 at 5:33 PM, Mahadevan R <mdevan.foobar at gmail.com
> >wrote:
>
> > On Thu, Jul 29, 2010 at 4:24 PM, Nitin Kumar <nitin.nitp at gmail.com>
> wrote:
> > > fine, but isn't there any way to hide few function of base class into
> > > derived one???
> >
> > You can try obscuring it:
> >
> > class y(x):
> >   def __init__(self):
> >       x.__init__(self)
> >        self.A = None
> >
>
> Trying to do something like this in Python shows a mistake
> in the design of your classes. There are different ways to
> do this in Python. Here are a few.
>
> 1. Prefix the function with double underscore ('__')
>  as steve said in his email.
>

I echo the same sentiments as Anand and Steve. If your class inherits from
something, its assumed the child class is of the same `kind` as the parent.

What you're asking sounds like this,

I have a `Vehicle` class which can `drive()`, now I wanna subclass `Car`,
but my `Car` doesnt implement `drive()` method.


Having said that, I'll add another method to restrict access to this
odd-function using __getattribute__.

What is __getattribute__ ?
  Whenever you do access an attribute, be it for a function or an attribute
(like obj.foo() or obj.value), obj.__getattribute__ is called. Things are
really a little more involved than the simple explanation I wrote, but for
this case you just need to know that much.


class Parent(object):
    def childShouldntCallMe(self):
       doParentStuff()


class Child(Parent):

    def __getattribute__(self, name):
         if name == "childShouldntCallMe":
             raise RestrictedAccessError # This could be a more polite
NotImplementedError
         else:
             return super(Child, self).__getattribute__(name)


/jeff


More information about the BangPypers mailing list