私有方法和私有变量的封装是类似的,只要在方法前面加上“__”就是私有方法了。
class Animal(object):
"""定义动物类"""
def __init__(self, age, sex=1, weight=0.0):
self.age = age
self.sex = sex
self.__weight = weight
def eat(self):
self.__weight += 0.2
print(self.__weight)
print("eat...")
self.__run()
def __run(self):
self.__weight -= 0.1
print("run...")
a1 = Animal(2, 0, 10.0)
# a1.run()
a1.eat()
私有方法可以在类的内部访问,不能在外部访问,否者会发生错误。
如果一定要在类的外部进行私有方法也是可以的。与私有变量类似,_类名__方法
,这样会破坏封装。