Python知识锦集

Python高级语法2:私有化、import、封装继承多态

2018-12-13  本文已影响3人  IIronMan

一、私有化

通过 name mangling (名字重整(目的就是防子类以重写基类的方法或者属性)如:_Class__object)机制就可以访问 private

class Person(object):

    def __init__(self,name,age,taste):

         self.name = name
         self._age = age
         self.__taste = taste

    def showperson(self):
        print(self.name)
        print(self._age)
        print(self.__taste)

    def dowork(self):
        self._work()

    def _work(self):
        print("my _work")

    def __away(self):
        print("my __away")


class Student(Person):

    def construction(self,name,age,taste):
        self.name = name
        self._age = age
        self.__taste = taste

    def showstudent(self):
        print(self._age)
        print(self.name)
        print(self.__taste)

    @staticmethod
    def testbug():
        _Bug.showbug()


class _Bug(object):

     @staticmethod
     def showbug():

        print("showbug")


s1 = Student('jack', 25, 'football')
s1.showperson()
print('*'*20)

# 无法访问__taste,导致报错
# s1.showstudent()
s1.construction('rose', 30, 'basketball')
s1.showperson()
print('*'*20)

s1.showstudent()
print('*'*20)

Student.testbug()

二、import 导入模块

三、多个模块 import 导入注意点(也就是公共模块的问题)

四、再议 封装、继承、多态

上一篇 下一篇

猜你喜欢

热点阅读