Python訪問限制

2021-07-03 11:50:50 字數 1209 閱讀 5926

我們可以給乙個例項繫結很多屬性,如果有些屬性不希望被外部訪問到怎麼辦?

python對屬性許可權的控制是通過屬性名來實現的,如果乙個屬性由雙下劃線開頭(__),該屬性就無法被外部訪問。看例子:

class person(object):

def __init__(self, name):

self.name = name

self._title = 'mr'

self.__job = 'student'

p = person('bob')

print p.name

# => bob

print p._title

# => mr

print p.__job

# => error

traceback (most recent call last):

file "", line 1, in attributeerror: 'person' object has no attribute '__job'

可見,只有以雙下劃線開頭的"__job"不能直接被外部訪問。

但是,如果乙個屬性以"__***__"的形式定義,那它又可以被外部訪問了,以"__***__"定義的屬性在python的類中被稱為特殊屬性,有很多預定義的特殊屬性可以使用,通常我們不要把普通屬性用"__***__"定義。

以單下劃線開頭的屬性"_***"雖然也可以被外部訪問,但是,按照習慣,他們不應該被外部訪問。

請給person類的__init__方法中新增namescore引數,並把score繫結到__score屬性上,看看外部是否能訪問到。

?不會了怎麼辦

以雙下劃線開頭的屬性無法被外部訪問,"__***__"除外。

參考**:

class person(object):

def __init__(self, name, score):

self.name = name

self.__score = score

p = person('bob', 59)

print p.name

print p.__score

python科技限制 python 訪問限制

class person object def run self print self.money print run def eat self,food print eat food def init self,name,age,height,weight,money self.name name...

Python 訪問限制

內部屬性不被外部訪問,可以把屬性的名稱前加上兩個下劃線 在python中,例項的變數名如果以 開頭,就變成了乙個私有變數 private 只有內部可以訪問,外部不能訪問 class student object def init self,name,score self.name name self...

python 訪問限制

class person object def init self,name,age,weight,height,money self.name name self.age age self.weight weight self.height height self.money money def ...