python

当前位置:首页 > python面向对象 > 当前文章

python面向对象

私有属性私有方法在子类中也不可以访问

2020-04-06 72赞 老董笔记
每篇文章努力于解决一个问题!更多精品可移步文章底部。

  私有属性私有方法在子类中也不可以访问,这个知识点需要单独感受下。

# -*- coding:utf-8 -*-

class Person:

    __Country = '华夏'

    def __init__(self,name,hobby):
        self.name = name
        self.__hobby = hobby

    def __skill(self):
        print('拳打脚踢')


class TianLong(Person):

    def __init__(self,name,hobby):
        super(TianLong, self).__init__(name,hobby)
        print('TianLong子类对象创建完毕')
        self.say()

    def echo(self):
        print(self.__Country)


class SheDiao(Person):

    def __init__(self,name,hobby):
        super(SheDiao, self).__init__(name,hobby)
        print('SheDiao子类对象创建完毕')

    def echo(self):
        print(self.__skill)


if __name__ =="__main__":
    p1 = TianLong('乔峰','喝酒')
    p2 = SheDiao('乔峰','喝酒')
    p1.echo()
    p2.echo() # 会报错 'SheDiao' object has no attribute '_SheDiao__skill'


TianLong子类对象创建完毕
Traceback (most recent call last):
  File "D:/py3script/python66/object/13_1_1.py", line 37, in <module>
    p1 = TianLong('乔峰','喝酒')
  File "D:/py3script/python66/object/13_1_1.py", line 20, in __init__
    self.say()
AttributeError: 'TianLong' object has no attribute 'say'

文章评论

私有属性私有方法在子类中也不可以访问文章写得不错,值得赞赏