Python类的定义与使用

类定义
# coding:utf-8

if __name__ == '__main__':

    '''
    定义:class 类名(object):
           类属性,方法等......
    实例化: 类名(无参|参数......)
    '''
    class A(object):
        pass
    a = A()
    print(a)  # <__main__.A object at 0x00D9DD50>
类方法定义
# coding:utf-8

if __name__ == '__main__':

    '''
    定义:通过def + 方法名(self,参数1,参数2......) self是必须的
    调用:object.方法名(参数1,参数2......)
    '''
    class B(object):
        sex = 'man'
        def talk(self, name):
            print(name)
    b = B()
    b.talk('ok')  # ok
类的继承
# coding:utf-8

if __name__ == '__main__':

    '''
    在声明类的时候指定这个类继承哪些类
    class 类名(extend1,extend2.......):
       属性,方法......
    extend1,extend2 代表要继承的类。可以一次性继承多个类
    继承顺序为从左到右,如果继承的方法或属性重复,以先继承的为主
    class.__mro__ 查看类的继承链
    '''
    class C(object):
        sex = 'woman'

        def see(self, name):
            print(f'看{name}')

        def talk(self, name):
            print(f'说{name}')

    class D(B, C):
          pass

    d = D()
    d.talk('yes')  # yes 不是 说yes  以先继承的为主
    d.see('书')  # 看书
    print(d.sex)  # man 不是 woman  以先继承的为主
    print(D.__mro__)  # (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>)
类的公有,私有
# coding:utf-8

if __name__ == '__main__':

    '''
    私有属性定义: __+变量名
    私有方法定义: __+函数名(self,参数1,参数2......)
    私有外部无法访问,只能内部访问。但是私有属性可以在外部通过object._+类名__+变量名 强制访问
    '''
    class E(object):
        __name = 'xie'
        sex = 'man'

        def __talk(self, name):
            print(name)

        def run(self):
            self.__talk('ok')

        def dp(self):
            print(self.__name)

    e = E()
    # print(e.__name) Error 外部无法访问私有属性 D
    print(e.sex)  # man
    # e.__talk('yes') Error 外部无法访问私有方法
    # object._+类名__+变量名 强制访问
    print(e._E__name)  # xie
    e.run()  # ok
    e.dp()  # xie
子类调用父类的方法
# coding:utf-8

if __name__ == '__main__':

    '''
    通过super().方法(参数1,参数2......)调用,该用法要求python版本3以上
    或
    supper(子类名,self).方法(参数1,参数2......)
    '''
    class F(object):
        def talk(self, name):
            print(f'super name is {name}')

    class G(F):
        def talk(self, children_name, super_name):
            self.print_children_name(children_name)
            super().talk(super_name)

        def talk2(self, children_name, super_name):
            self.print_children_name(children_name)
            super(G, self).talk(super_name)

        def print_children_name(self, name):
            print(f'children name is {name}')


    g = G()
    g.talk('小明', '大明')  # children name is 小明 super name is 大明
    g.talk2('小明', '大明')  # children name is 小明 super name is 大明
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值