iT邦幫忙

DAY 28
0

Python初學起步走系列 第 28

[Python初學起步走-Day28] - 物件導向(Object-oriented,OO) - 私有屬性、私有方法

在Python中,所有的類別的屬性、方法預設都是公開(public):外部可存取

#myclass.py
class Human:
    def __init__(self,h=0,w=0):
        self.height=h
        self.weight=w
    def BMI(self):
        return self.weight / ((self.height/100)**2)





#main.py
import myclass
a = myclass.Human(180,80)
print(a.height,a.weight)
print(a.BMI())

若我們想做到類別內部的屬性、方法不給外部做直接存取,就要把該屬性、方法設為私有

Python中只要在屬性、方法前加上 __ 即可成為私有屬性或私有方法(外部無法存取),可達到較好的封裝性

#myclass.py
class Human:
    def __init__(self,h=0,w=0):
        self.__height=h
        self.__weight=w
    def __BMI(self):
        return self.__weight / ((self.__height/100)**2)
   






#main.py
import myclass
a = myclass.Human(180,80)
print(a.__height,a.__weight)
#AttributeError: 'Human' object has no attribute '__height'
print(a.BMI())
#AttributeError: 'Human' object has no attribute 'BMI'

可以利用其他類別內部的函式直接存取私有方法(間接存取)

#myclass.py
class Human:
    def __init__(self,h=0,w=0):
        self.__height=h
        self.__weight=w
    def __BMI(self):
        return self.__weight / ((self.__height/100)**2)
    def getBMI(self):
        return self.__BMI()
    def getHeight(self):
        return self.__height
    def getWeight(self):
        return self.__weight
    def setWeight(self,w):
        self.__weight=w





#main.py
import myclass
a = myclass.Human(180,80)
print(a.getHeight(),a.getWeight())
print(a.getBMI())
a.setWeight(60)
print(a.getHeight(),a.getWeight())


上一篇
[Python初學起步走-Day27] - 物件導向(Object-oriented,OO) - 特殊方法(運算子)
下一篇
[Python初學起步走-Day29] - 檔案讀寫
系列文
Python初學起步走30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言