Python物件導向之私有屬性和方法

2021-09-29 20:05:48 字數 2931 閱讀 6070

定義方式

在定義屬性或者方法時,在屬性名或者方法名前面增加兩個下劃線,定義的就是私有屬性或方法;

沒使用私有屬性前

class women:

def __init__(self, name, age):

self.name = name

self.age = age

def secret(self):

print("%s 的年齡是 %d" % (self.name, self.age))

xiaohong = women("小紅", 18)

print(xiaohong.age) # 18

xiaohong.secret() # 小紅 的年齡是 18

使用私有屬性後

class women:

def __init__(self, name, age):

self.name = name

self.__age = age

def secret(self):

print("%s 的年齡是 %d" % (self.name, self.__age))

xiaohong = women("小紅", 18)

# 不能在外部直接通過物件呼叫私有屬性

# print(xiaohong.age) # 報錯 attributeerror: 'women' object has no attribute 'age'

# 但還是能通過內部方法呼叫物件的私有屬性

xiaohong.secret() # 小紅 的年齡是 18 公有方法還是能夠呼叫私有屬性

使用私有方法後

class women:

def __init__(self, name, age):

self.name = name

self.__age = age

def __secret(self):

print("%s 的年齡是 %d" % (self.name, self.__age))

xiaohong = women("小紅", 18)

# 當設定私有方法後,外部就不能呼叫私有方法了

# xiaohong.__secret() # 報錯 attributeerror: 'women' object has no attribute '__secret'

在python中,並沒有真正意義上的私有,只有偽私有;

破解私有屬性和私有方法

class women:

def __init__(self, name, age):

self.name = name

self.__age = age

def __secret(self):

print("%s 的年齡是 %d" % (self.name, self.__age))

xiaohong = women("小紅", 18)

# 當設定私有方法後,外部就不能直接呼叫私有方法了

# xiaohong.__secret() # 報錯 attributeerror: 'women' object has no attribute '__secret'

# 破解私有屬性和私有方法,但不建議使用

print(xiaohong._women__age) # 18

xiaohong._women__secret() # 小紅 的年齡是 18

但注意,在日常開發中,不要使用這種方式訪問物件的私有屬性或者私有方法!!我們只需要用提供的公共方法來簡介呼叫私有方法或屬性即可。

子類物件不能在自己的方法內部,直接訪問父類的私有屬性和私有方法;

子類物件可以通過父類的共有方法,間接訪問到私有屬性和私有方法。

私有屬性,方法,是物件的隱私,不對外公開,外界以及子類,都不能直接訪問;

私有屬性,方法通常用來做一些內部的事情;

子類物件,可以呼叫父類的公有方法和公有屬性;

而如果父類中的公有方法 有呼叫父類的私有屬性的話,那麼我們也可以通過呼叫父類的公有方法來間接呼叫父類的私有屬性和方法。

class women:

def __init__(self, name, age):

self.name = name

self.__age = age

def __secret(self):

print("私有:%s 的年齡是 %d" % (self.name, self.__age))

def public(self):

print("公有:%s 的年齡是 %d" % (self.name, self.__age))

self.__secret()

class girl(women):

def test(self):

print("你的姓名是 %s" % self.name)

# print("你的年齡是 % d" % self.__age) # 不能在子類中直接呼叫父類的私有屬性

# self.__secret() # 不能在子類中直接呼叫父類的私有方法

# 可以通過呼叫父類的公有方法來簡介呼叫父類的私有屬性和方法

self.public() # 執行結果:(公有:xiaohong 的年齡是 18 私有:xiaohong 的年齡是 18)

print("...")

xiaohong = girl("xiaohong", 18)

# 子類的物件不能在外部直接呼叫父類/祖父類的私有屬性和方法

# print(xiaohong.__age)

# print(xiaohong.__secret)

xiaohong.test()

python物件導向之私有屬性和私有方法

前面帶兩個下劃線表示對變數進行私有化 外部不能隨便的訪問和更改 class student object def init self,name,score 前面帶兩個下劃線表示對變數進行私有化 外部不能隨便的訪問和更改 self.name name self.score score def get ...

Python物件導向06 私有屬性和私有方法

應用場景 定義方式 class women def init self,name self.name name 不要問女生的年齡 self.age 18 def secret self print 我的年齡是 d self.age xiaofang women 小芳 私有屬性,外部不能直接訪問 pr...

python物件導向學習(三)私有屬性和私有方法

目錄在j a或者其他的程式語言中,使用訪問修飾符來限制屬性和方法的訪問級別,一般有public protected default private這四種級別,但是python中是不同的。應用場景 定義方式 class person def init self self.name zfx self.a...