views:

1685

answers:

8

Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :

class A:
    def __init__(self):
        #do something here

    def method(self):
        #some code here

class B(A):
    def __init__(self):
        A.__init__(self)
        #additional initialization goes here

    def method(self):
        #this overrides the method ( and possibly make it private here )

from this point forward , I don't want any class that extends from B to be able to call method . Is this possible ?

EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.

+4  A: 

To make a method sort of private, you can name-mangle a method like so:

class Foo:
    def __blah():
        pass

class Bar(Foo):
    def callBlah():
        self.__blah() # will throw an exception

But subclasses can still find your methods through introspection if they really want to.

But Python (by deliberate design and choice) has no notion of private members.

Dana
What about replacing the method with getattr/setattr ? Will that work ? Even if I lose the method ...
Geo
I think you could replace the property so that they call something like: subclassInstance.foo(), it'll throw an exception. But I think they'll still be able to call SuperClass.foo(subclassInstance) and still get at it. There may be more metaprogramming wizardry possible, but none that I know of.
Dana
+14  A: 

There's no way to truly do this in Python. Rather unpythonic, it is.

As Guido would say, we're all consenting adults here.

Here's a good summary of the philosophy behind everything in Python being public.

Triptych
+1 for the Yoda styled answer ;-)
Sean
+11  A: 

Python is distributed as source. The very idea of a private method makes very little sense.

The programmer who wants to extend B, frustrated by a privacy issue, looks at the source for B, copies and pastes the source code for method into the subclass C.

What have you gained through "privacy"? The best you can hope for is to frustrate your potential customers into copying and pasting.

At worst, they discard your package because they can't extend it.

And yes, all open source is extended in one way or another. You can't foresee everything and every use to which you code will be put. Preventing some future use is hard to do when the code is distributed as source.

See http://stackoverflow.com/questions/261638/how-do-i-protect-python-code


Edit On "idiot-proof" code.

First, python is distributed as source 90% of the time. So, any idiot who downloads, installs, and then refuses to read the API guide and calls the methods out of order still has the source to figure out what went wrong.

We have three classes of idiots.

  • People who refuse to read the API guide (or skim it and ignore the relevant parts) and call the methods out of order in spite of the documentation. You can try to make something private, but it won't help because they'll do something else wrong -- and complain about it. [I won't name names, but I've worked with folks who seem to spend a lot of time calling the API's improperly. Also, you'll see questions like this on SO.]

    You can only help them with a working code sample they can cut and paste.

  • People who are confused by API's and call the methods every different way you can imagine (and some you can't.) You can try to make something private, but they'll never get the API.

    You can only help them by providing the working code sample; even then, they'll cut and paste it incorrectly.

  • People who reject your API and want to rewrite it to make it "idiot proof".

    You can provide them a working code sample, but they don't like your API and will insist on rewriting it. They'll tell you that your API is crazy and they've improved on it.

    You can engage these folks in an escalating arms race of "idiot-proofing". Everything you put together they take apart.

At this point, what has privacy done for you? Some people will refuse to understand it; some people are confused by it; and some people want to work around it.

How about public, and let the folks you're calling "idiots" learn from your code?

S.Lott
Well , I would like to kinda make the class "idiot proof" , as in , you can only call about 2 methods , which will do everything is needed . I don't want users to call methods in wrong order . Does this make sense ?
Geo
Python *can* be distributed in compiled form, it just usually isn't.
Triptych
Donovan, the correct way of preventing them being called in the wrong order would be some state to prevent exactly that: raise RuntimeError("You must first call method1")
Ali A
+1 for making me think, but python's "everything is public" agreement still makes me feel like something is missing. If you were distributing a C++ opensource library, would you declare all members and methods as public? No. No, you wouldn't. And why not?
Federico Ramponi
Your arguments are not against private members in Python; they are against information hiding in general. Why does information hiding make sense in C++ and Java but not in Python?
Federico Ramponi
The best answers a Pythonist can provide are, in general, "because that wouldn't be pythonic", or "because Guido would say ...". But these answers beg the question.
Federico Ramponi
Indeed, the real question is, *is information hiding useful or not?* If not, C++ and Java are messing up things for no reason. If yes, as I think, something is missing in Python.
Federico Ramponi
"information hiding" is a metaphor. Not a design goal or even a technical feature of any value. Private is a fussy legalistic declaration that allows change without notice. It generally *does* mess things up for no real value.
S.Lott
See also: http://groups.google.com/group/comp.lang.lisp/msg/917737b7cc8510e3
Jouni K. Seppänen
Information hiding is documentation. By removing crud from the API, the API becomes easier to learn. Go work on code with 150,000 methods, none of them private, and then see if you still feel like calling people idiots.
joeforker
@Daniel Holth: There's the documented API and there's the "private" keyword. Python has names that begin with "_", which are not literally "private" but are not part of the documented API. I never say "idiot-proof" because I do NOT agree that any other programmer is an idiot.
S.Lott
+3  A: 

This may be a fair approximation. Lexical scoping to the "rescue":

#!/usr/bin/env python

class Foo(object):
    def __init__(self, name):
        self.name = name
        self.bar()

    def bar(self):
        def baz():
            print "I'm private"
            print self.name

        def quux():
            baz()

        self.quux = quux


if __name__ == "__main__":
    f = Foo("f")
    f.quux()

    g = Foo("g")
    g.quux()

    f.quux()

Prints:

I'm private
f
I'm private
g
I'm private
f
joeforker
+3  A: 

I am surprised that no one has mentioned this, but prefixing the method name with a single underscore is the correct way of labelling it as "private". It's not really private of course, (as explained in other answers), but there you go.

def _i_am_private(self):
    """If you call me from a subclass you are a naughty person!"""
Ali A
+5  A: 

You can prefix methods and members with a single or double underscore. A single underscore implies "please don't use me, I'm supposed to be used only by this class", and a double underscore instructs the Python compiler to mangle the method/member name with the class name; as long as the class and its subclasses don't have the same name, the methods/members can be considered "private".

However, the solution to your requirements so far is to write clear documentation. If you don't want your users to call methods in the wrong order, then say so in the documentation.

After all, even C++ privates aren't that private. For example think the old trick:

#define private public
#include <module>
ΤΖΩΤΖΙΟΥ
+2  A: 

Changing an inherited method from public to private breaks inheritance. Specifically, it breaks the is-a relationship.

Imagine a Restaurant class with a open-doors public method (i.e. it's dinnertime and we want to flip the front door sign from closed to open). Now we want a Catering class that would share many of the implementation details of Restaurant (they both need cooks, kitchens, dishes, food suppliers, and maybe even waitstaff), but not have a dining area, front doors, or the open-doors method. Inheritance from Restaurant is a mistake! It might appear that all you need to do is change the open-doors method to private so no one can use it, but then "any Catering object is-a Restaurant" is false, since part of Restaurant's public interface is open-doors. It's better to refactor Restaurant by adding a new base class and then both Restaurant and Catering derive from it.

Languages with a notion of protected or private inheritance support this idea of inheritance for implementation only, but Python is not one of those. (Nor is it useful in those languages, except rarely.) Usually when non-public inheritance is sought, containment (aka "has-a relationship") is the better path, you can even make the attribute protected or private.

Python spells protected with a single leading underscore and private with double leading underscores, with the modification of the "consenting adults" philosophy mentioned in Triptych's answer. "Dangerous" attributes and methods of your class, e.g. ones that might cause data loss, should be non-public (whether to make them protected or private is influenced by other factors), with public methods used to provide a simpler, safer interface.

Roger Pate
+2  A: 

"Everything must be public" proponents think the author is trying to hide a useful API from the users. This guy doesn't want to violate an unquestionable law of Python. He wants to use some methods to define a useful API, and he wants to use other methods to organize the implementation of that API. If there's no separation between the two it doesn't mean the author is not an idiot. It means the author was too lazy to actually define an API.

In Python, instead of marking properties or methods as private, they may be prefixed with _ as a weak "internal use" indicator, or with __ as a slightly stronger one. In a module, names may be prefixed with _ in the same way, and you may also put a sequence of strings that constitute the modules' public API in a variable called __all__.

A foolish consistency is the hobgoblin of little minds.

joeforker