Close access to the base class public methods

Chris Rebert clp at rebertia.com
Tue Nov 11 14:41:05 EST 2008


On Tue, Nov 11, 2008 at 11:16 AM, RinKaMeAri <maxygd at gmail.com> wrote:
> On Nov 11, 9:12 pm, Steve Holden <st... at holdenweb.com> wrote:
>> RinKaMeAri wrote:
>> > Hi!
>> > Could you imagine any way to block access to the base class public
>> > methods?
>> > Here is an example:
>> > class B:
>> >     def public_method():
>> >         pass
>>
>> > class A(B):
>> >     def public_a_method():
>> >          pass
>>
>> > def a = A()
>>
>> > Is there any way to block the call a.public_method() without any
>> > changes to B class?
>> > Thank you!
>>
>> The simplest way would be to override B.public_method within A by
>> defining A.public_method to raise a NotImplementedError or similar
>> exception. Though of course this then begs the question of why A would
>> need to subclass B in the first place, but I assume there would be
>> methods you *did* want to implement.
>>
 <snip>
>
> BTW, what do you mean "to subclass B in the *first place*"?

Because you're inheriting from A and yet you don't want to inherit a
certain part of A, in this case public_method(), it's usually a sign
something is wrong with your class hierarchy; otherwise, you could
just inherit from something else which would have just the part of A
you want to inherit; it's a so-called "code smell", specifically
Refused Bequest I believe.

See this link into Fowler's Refactoring for more info on Refused
Bequest and the other code smells:
http://books.google.com/books?id=1MsETFPD3I0C&pg=PA87&lpg=PA87&dq=refused+bequest&source=bl&ots=pKN4o0QJc7&sig=rYT4lfWxhKijvNHpLYqk8DY5Epw&hl=en&sa=X&oi=book_result&resnum=3&ct=result

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list