python之类的私有化属性

掌握类的私有化属性

a.私有化属性的表示方法
b.访问私有化属性的方法
c.注意事项

a.私有化属性的表示方法
class student:
    def __init__(self):
        self.__number=30

banji=student()
print(banji.__number)
#注意:__number就是私有化属性

b.私有化属性的访问方法:私有化属性无法通过类名或者实例化对象访问,只能通过内部方法访问(可以理解为局部变量)
 

class student:
    def __init__(self,num):
        self.__num=num
    def print_name(self):
        print('your age is %d'%self.__num)
age=student(30)
age.print_name()

c.注意事项
python中没有c++,java等private、public这种关键字区分共有属性和私有属性,它是以__开头,否则为共有属性

猜你喜欢

转载自blog.csdn.net/YeChao3/article/details/82383776