how to use private method in a class

Basilisk96 basilisk96 at gmail.com
Mon May 21 23:48:52 EDT 2007


On May 21, 9:49 pm, "wang frank" <f... at hotmail.co.jp> wrote:
> Hi,
>
> I am trying to write a python class with a new data type such as:
> class Cc14:
>        def __init__(self, realpart, imagpart):
>                  self.r=realart
>                  self.i=imagpart
>
>        def __saturator(x):
>                  return x+1
>        def out(self,x):
>                  return Cc14(__saturator(x.r), __saturator(x,i))
>
> When I use the method out such as:
> z.out
>
> Python complains:
>
> global name '_Cc14_saturator' is not defined.
>
> Is the way put two underscore in front of the definitio making the method
> becomes private?
>
> Why in the same clase, I could not use the __saturator method?
>
> Thanks
>
> Frank
>

It seems you have several issues here:

(1) To avoid syntax errors,
  self.r=realart
should be:
  self.r=realpart

(2) Your __saturator method definition needs the reference to self:
  def __saturator(self, x):

(3) And lastly, the body of the out() method needs two corrections:
  return Cc14(self.__saturator(x.r), self.__saturator(x.i))

Is it really necessary to "privatize" the saturator method? In Python,
all class methods are public and visible by default. A method name
__methodname in a class "foo" turns into "_foo__methodname" in an
instance of the class. This is known as name mangling. It is simply a
convention supported by Python when a class attribute name begins with
two underscores. It prevents a programmer from calling something like
C.__saturator(arg), but still allows calling C._Cc14__saturator(arg).

IMHO, you could just leave the saturator definition as "def
saturator(self, x):"

Anyway, in your case the 3 fixes above will allow you now to do this:

>>>C = Cc14(2,3)
>>>result = C.out(C)
>>>result.r, result.i
(3, 4)

Which is beginning to look like your design intent..

Cheers,
-Basilisk96




More information about the Python-list mailing list