python爲何有私有方法和變量

1. 訪問安全,其實也沒有決定的安全安全

>>> class humer(object):
...   def __init__(self, name):
...     self.name = name
...   def num(self):
...     print self.name
...   def __inner(self):
...     print 'this is inner'

此時訪問__inner方法只能這樣this

>>> p._humer__inner()
this is inner
不然會報錯spa

 

2. 在子類繼承父類時,若是有相同的方法和變量的話,而咱們想使用各自的方法和變量。此時就可使用私有方法code

class Foo(object):
    def __init__(self):
        self.__baz = 42
    def foo(self):
        print self.__baz

class Bar(Foo):
    def __init__(self):
        super(Bar,self).__init__()
        self.__baz = 21
    def bar(self):
        print self.__baz

>>> b = Bar()
>>> b.foo()
42
>>> b.bar()
21

#若是沒有使用私有方法的話,那麼foo和bar的值將都是子類的值
相關文章
相關標籤/搜索