[BangPypers] how to delete base class attribute

Anand Balachandran Pillai abpillai at gmail.com
Thu Jul 29 15:04:12 CEST 2010


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.
2. Override the function accessing method using
a decorator and put the logic in the decorator to return
None if a specific function is accessed.
3. Raise NotImplementedError if the calling class
is not the super class.

I have given sample code for (3) here.

class A(object):

    def f1(self):
        print 'Hi'

    def f2(self, x):
        if self.__class__.__name__ != 'A':
            raise NotImplementedError
        print x

class B(A):
    pass

if __name__ == "__main__":
    a=A()
    a.f1()
    a.f2(10)

    b=B()
    b.f1()
    # Will raise exception
    b.f2(20)


However it is better to look at why you need it than
to use any of these approaches and correct that requirement.
Normally in Python, you never need a requirement like this.

HTH.

--Anand



>
> Cheers,
> -MD.
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>



-- 
--Anand


More information about the BangPypers mailing list