Day_13_AM_Private_Property_and_Method
# 面向对象的特征:
# 1. 封装
# 2. 继承
# 3. 多态(了解)
# 1. 封装
# 封装了属性和方法
# Python中没有: private protect public
# 类
class Person:
def __init__(self, name, age, sex):
self.name = name # 公有属性
self.__age = age # 私有属性: 双下划綫开头, 只能在当前类的内部使用
self._sex = sex # 公有属性, 但是不建议这样写
def run(self):
print(self.__age)
self.__eat()
# 私有方法
def __eat(self):
print('eat')
# 对象
p = Person('鹿晗', 30, '男')
print(p.name)
# print(p.__age) # 报错,__age是私有属性
print(p._sex)
p.run()
print()
# p.__eat() # 报错,__eat()是私有方法
# 下面的方式可以调用私有属性或私有方法, 但是不要这么用
# print(p._Person__age)
# p._Person__eat