-
如果需要修改一個物件的屬性值,通常有2種方法
- 物件名.屬性名 = 資料 ----> 直接修改
- 物件名.方法名() ----> 間接修改
-
私有屬性不能直接訪問,所以無法通過第一種方式修改,一般的通過第二種方式修改私有屬性的值:定義一個可以呼叫的公有方法,在這個公有方法內訪問修改,
class Master(object):
def __init__(self):
self.kongfu = "古法煎餅果子配方"
def make_cake(self):
print("[古法] 按照 <%s> 制作了一份煎餅果子..." % self.kongfu)
class School(object):
def __init__(self):
self.kongfu = "現代煎餅果子配方"
def make_cake(self):
print("[現代] 按照 <%s> 制作了一份煎餅果子..." % self.kongfu)
class Prentice(School, Master):
def __init__(self):
self.kongfu = "貓氏煎餅果子配方"
# 私有屬性,可以在類內部通過self呼叫,但不能通過物件訪問
self.__money = 10000
# 現代軟體開發中,通常會定義get_xxx()方法和set_xxx()方法來獲取和修改私有屬性值,
# 回傳私有屬性的值
def get_money(self):
return self.__money
# 接收引數,修改私有屬性的值
def set_money(self, num):
self.__money = num
def make_cake(self):
self.__init__()
print("[貓氏] 按照 <%s> 制作了一份煎餅果子..." % self.kongfu)
def make_old_cake(self):
Master.__init__(self)
Master.make_cake(self)
def make_new_cake(self):
School.__init__(self)
School.make_cake(self)
class PrenticePrentice(Prentice):
pass
damao = Prentice()
# 物件不能訪問私有權限的屬性和方法
# print(damao.__money)
# damao.__print_info()
# 可以通過訪問公有方法set_money()來修改私有屬性的值
damao.set_money(100)
# 可以通過訪問公有方法get_money()來獲取私有屬性的值
print(damao.get_money())
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/39723.html
標籤:Python
上一篇:面向物件-私有權限
下一篇:面向物件--多型
