2011/06/11

Private method HOWTO in python

main.py
# -*- coding: utf-8 -*-                                                       

import os
import mycls


def main():
    henley = mycls.ITWorkers('PHP', 'Henley', 'web creator', 'henley@livegate.com', 32, 700)

    henley.OS = 'Mac'
    henley.work(8)
    """                                                                       
    '_' はPEP8にて外部公開していないメソッドの                   
    命名規則として用いることが推奨されている。だが、外部から                  
    呼び出すことは可能                                                        
    """
    henley._printme('test')
    """                                                                       
    '__' は外部から呼び出すことができない                        
    ただ、この使用方法はPEP8に準拠していない                                  
    """
    henley.__printme('test')


if __name__ == "__main__":
    main()

mycls.py
# -*- coding: utf-8 -*-                                                       

import os


class Workers:
    """ This is a class of workers working in the company """
    def __init__(self, name, position, email, age, salary):
        self.name = name
        self.position = position
    self.email = email
        self.age = age
        self.salary = salary


class ITWorkers(Workers):
    """ This is a class of IT engineers. """
    OS = 'WinNT'

    def __init__(self, language, *av):
        Workers.__init__(self, *av)
        self.language = language

    def _printme(self, name):
    print 'my name is %s.' % (name)

    def __printme(self, name):
    print 'my name is %s.' % name

    def work(self, n):
    """ IT engineers should work. """

    if self.position == 'web creator':
            w = 'makes web site'
    elif self.position == 'server administrator':
            w = 'checks the traffic'
    elif self.position == 'programmer':
            w = 'write program'

    print '%s, %s for %d, hours using %s on %s' % (self.name, w, n, self.language, self.OS)
    self._printme(self.name)
    self.__printme(self.name)

Test....
> python main.py
Henley, makes web site for 8, hours using PHP on Mac
my name is Henley.
my name is Henley.
my name is test.
Traceback (most recent call last):
  File "main.py", line 29, in <module>
    main()
  File "main.py", line 25, in main
    henley.__printme('test')
AttributeError: ITWorkers instance has no attribute '__printme'

No comments:

Post a Comment

100