zoukankan      html  css  js  c++  java
  • python——面向对象,继承

    """
    继承:子类继承父类
    1.单继承,多继承
    2. 子类调用或重用父类的同名属性和方法
    3. 多层
    4.私有属性和私有方法
    class 类名(object<父类>
    """

    '''单继承'''
    # # 父类
    # class A(object):
    # def __init__(self):
    # self.num = 1
    #
    # def info_print(self):
    # print(self.num)
    #
    #
    # # 子类
    # class B(A):
    # pass
    #
    #
    # def main1():
    # r = B()
    # r.info_print() # 1

    """
    多继承:默认使用第一个父类的同名属性和方法
    重写:若子类和父类有同名属性和方法,则调用子类的
    子类调用父类的同名属性和方法:注意 self
    多层继承, 父子孙

    super:子类重写了父类方法,并在重写方法中调用父类方法
    super(当前类,self).当前方法
    私有属性:限制继承,在属性名和方法名前面加上两个__,
    只能在类里面访问,获取get_xx,修改set_xx
    """


    def __info_prin():
    print('这是私有方法')


    class Master:
    def __init__(self):
    self.kongfu = '[古法煎饼]'
    self.__money = 10000 # 私有属性

    def __make_cake(self):
    return f'{self.kongfu}制作煎饼果子'
    f'花费了{self.__money}'


    # t1 = Master()
    # print(t1._Master__money)
    # # 10000 ,运用命名的变换成功访问私有属性
    # print(t1._Master__make_cake)
    # # 打印了t1地址,需有一个变量来接收

    """
    另一种理解:
    实际上私有属性存在一个坑点,即通过换名仍然可以访问私有属性;
    命名时最好以_开头(一种规范);
    getter(访问器)setter(修改器)来访问与修改属性值;
    @property装饰器 来包装gettersetter方法;
    """


    class School:
    def __init__(self, kongfu, money):
    self._kongfu = kongfu
    self._money = money

    # 访问器 - getter方法
    @property
    def money(self):
    return self._money

    @property
    def kongfu(self):
    return self._kongfu

    # 修改器 - setter方法
    @money.setter
    def money(self, money):
    self._money = money

    def make_cake(self):
    print(f'{self._kongfu}制作煎饼{self._money}')


    # school = School('有名法', 100)
    # school.make_cake()
    # school.money = 10
    # school.make_cake()
    # # school.kongfu = '古法' AttributeError: can't set attribute


  • 相关阅读:
    SpringBoot20 集成SpringSecurity02 -> 利用SpringSecurity进行前后端分离的登录验证
    Angular问题04 模块导入错误???、BrowserModule模块重复加载???、material模块引入后报错
    基于http的多进程并发文件服务器
    准备面试的那些事儿2
    ubuntu中解决/usr/bin/ld: cannot find -lxxx
    kafka学习之相关命令
    linux中制作动态库
    kafka之c接口常用API------librdkafka
    kafka入门:简介、使用场景、设计原理、主要配置及集群搭建(转)
    <c和指针>学习笔记6输入输出函数
  • 原文地址:https://www.cnblogs.com/kekefu/p/12301266.html
Copyright © 2011-2022 走看看