Defining a method final

Eric Brunel eric.brunel at pragmadev.com
Tue Jun 11 11:35:30 EDT 2002


Emile van Sebille wrote:
> Accepted practice is to use a single underscore for objects to be
> considered private.  This does not prevent their use, but strongly
> signals that re-use ought not to be done.
> 
>>>> class Test:
> ...     def _private(self): pass
> ...
> 

Python now have an "official" means to make attributes private by prefixing 
them with a double-underscore. And it *does* prevent their use or 
overloading:

class A:
  def __private(self): pass
class B(A):
  pass
o = B()
o.__private()

results in:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: B instance has no attribute '__private'

Regarding the original question (final methods), it has however obvious 
drawbacks:
- the method can be *redefined*: that doesn't mean it can be overloaded, 
but class B can have its own __private method
- the method is actually *private*, which means that neither sub-classes, 
nor "outside" classes can call it.

I don't think that actual final methods can be defined in Python...
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list