DAY 28
0

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

``````#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初學起步走30