1. Private authority
2. The private properties and private methods of the class cannot be directly accessed through the object, but they can be called through self inside the class
class Student():
name='jack'
__age=13
def play(self): #实例化方法
print('他喜欢运动')
def __eat(self):
print('他喜欢吃零食')
def self(self):
return self.__eat()
a=Student()
print(a.name)
print(a.age)
a.play()
a.self()
class Student():
name='jack'
__age=13
def play(self): #实例化方法
print('他喜欢运动')
def __eat(self):
print('他喜欢吃零食')
def self(self):
print('年龄:',self.__age)
return self.__eat()
a=Student()
print(a.name)
a.play()
a.self()
返回结果:
jack
他喜欢运动
年龄: 13
他喜欢吃零食
3. The private properties and private methods of the class will not be inherited by subclasses, and subclasses cannot access them
class Animal():
def __init__(self):
self.name='动物'
self.__sex='雄性或者雌性'
def play(self):
print('动物都有自己的玩法')
def __eat(self):
print('动物都会捕食')
def info(self):
return self.__eat()
class Cat(Animal):
pass
c=Cat()
print(c.name)
print(c.sex)
c.play()
c.info()
4. Modify the value of a private property
class Person():
age=20
def __init__(self):
self.__money=100
#set_xxx()方法 接收参数,修改私有属性的值
def set_money(self,money):
self._money=money
#get_xxx()方法 返回私有属性的值
def get_money(self):
return self._money
p=Person()
#实例对象修改类属性
p.age=18
print(p.age)
p.set_money(5000)
print(p.get_money())
返回值:
18
5000