somepeople

python面向对象之封装

封装(变形)attribute变为_类名__AttrName

封装的特点:

1.在类外部无法直接obj.__AttrName
在类定义阶段,类的属性已变形为_类名__AttrName

所以类外部生成的实例对象就无法直接调用__AttrName,但可以调用_类名__AttrName


class Students:
def __init__(self,name,age,sex):
self.__name = name
self.__age = age
self.__sex = sex


s1 = Students('ryan',18,'man')
print(s1._Students__name)
#ryan

2.在类内部是可以直接使用:obj.__AttrName

因为在类内部的属性均会在定义阶段自动变形为_类名__AttrName,是可以互相调用的

class Students:
    def __init__(self,name,age,sex):
        self.__name = name
        self.__age = age
        self.__sex = sex
    def info(self):
        print('Im %s Im %s years old ,Im a %s'%(self.__name,self.__age,self.__sex))


s1 = Students('ryan',18,'man')
s1.info()
print(s1._Students__name)
#Im ryan Im 18 years old ,Im a man
#ryan

3.子类无法覆盖父类__开头的属性

不同的类封装后变形为不同的类名属性

class Students:
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex
    def __info(self):
        print('parentsclass')
        print('Im %s Im %s years old ,Im a %s'%(self.name,self.age,self.sex))




class TeenStudents(Students):
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex
    def __info(self):
        print('subclass')
        print('Im %s Im %s years old ,Im a '%(self.name,self.age))

s1 = TeenStudents('ryan',18,'man')
s1._Students__info()
s1._TeenStudents__info()
print(s1.name)
#parentsclass
#Im ryan Im 18 years old ,Im a man
#subclass
#Im ryan Im 18 years old ,Im a 
#ryan

 

posted on 2020-09-02 20:00  Hello_Thanos  阅读(124)  评论(0编辑  收藏  举报

导航