網頁

2015年7月2日 星期四

[Python] 雙底線的用處

目的: 了解雙底線的用處

1. 不可繼承
2. public
3. 不管是class member或method都遵循這個規則

以下用class method舉例:
#!/usr/bin/python

class A(object):
        def __init__(self):
                pass

        def test1(self):
                print "test1"
        def __test2(self):
                print "test2"

class B(A):
        def __init__(self):
                pass

b = B()
b.test1()
b.__test2()
結果:(注意test1有印出來但呼叫__test2時發生AttributeError的Exception)
test1
Traceback (most recent call last):
  File "./private.py", line 18, in 
    b.__test2()
AttributeError: 'B' object has no attribute '__test2'

沒有留言:

張貼留言