2

I remember that there is some sort of syntax that will make a function of a class only callable by that class and not by any subclasses that inherit the functions of that class, but I can't recall exactly what it is and google has been of no help to me. Can anyone remind me how I would go about doing this?

user3002473
  • 4,835
  • 8
  • 35
  • 61
  • That's not the done thing in python, so there's no simple way to do it. – sapi Dec 16 '13 at 01:13
  • Why would you want to do this? If you have a subclass of something, it should have all of the methods of that class. –  Dec 16 '13 at 01:18

3 Answers3

5

You can't enforce the privacy, but starting a method name with double underscores is the idiomatic Python way to indicate that the method should not be used by subclasses.

Community
  • 1
  • 1
Sam Mussmann
  • 5,883
  • 2
  • 29
  • 43
  • Thanks, that's exactly what I was thinking of. If I did ever need to strictly enforce the usage of the function to one class I would indeed just use Hyperboreus' answer, but the underscore syntax is the way I had in mind. – user3002473 Dec 16 '13 at 01:17
  • @user3002473 Glad to hear that, because my answer may be correct, but I wouldn't advise using it myself. – Hyperboreus Dec 16 '13 at 01:18
2

This works, but I think it is a bit of an anti-pattern:

class A:
    def f(self):
        if type(self) != A:
            raise NotImplementedError('Thou shalt not invoke this here method.')
        print('good')

class B(A): pass

A().f()
B().f()

But actually, please don't use it. Stick to the normal underscore and dunder notation with the implied name-wrangling. We are all adults around here. Especially as my approach can be easily broken from the outside:

type_ = type
type = lambda x: A
B().f()
type = type_
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
0

I know, this is not an answer to your question, but you should really consider rethinking your object structure since you are violating the common principles of object oriented programming.

OBu
  • 4,977
  • 3
  • 29
  • 45