Why are Python's 'private' methods not actually private?

后端 未结 12 2277
不思量自难忘°
不思量自难忘° 2020-11-22 02:50

Python gives us the ability to create \'private\' methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod()

12条回答
  •  野性不改
    2020-11-22 03:18

    Example of private function

    import re
    import inspect
    
    class MyClass :
    
        def __init__(self) :
            pass
    
        def private_function ( self ) :
            try :
                function_call = inspect.stack()[1][4][0].strip()
    
                # See if the function_call has "self." in the begining
                matched = re.match( '^self\.', function_call )
                if not matched :
                    print 'This is Private Function, Go Away'
                    return
            except :
                print 'This is Private Function, Go Away'
                return
    
            # This is the real Function, only accessible inside class #
            print 'Hey, Welcome in to function'
    
        def public_function ( self ) :
            # i can call private function from inside the class
            self.private_function()
    
    ### End ###
    

提交回复
热议问题