在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())