【飞桨学习】Python面向对象入门

Python面向对象

类的定义

class Athlete:
    # 类属性
    Athlete_about = "这是一个运动员类"

    # 构造方法
    def __init__(self, name, times):
        self.name = name
        self.times = times
        self.Athlete_about = "这不是"

    # 方法
    def show(self):
        print(f"{self.name}:{self.times}")

    # 类方法
    @classmethod
    def showMe(self):
        print(self.Athlete_about)


amy = Athlete("amy", ['2.23', '3.44'])
amy.show()

self代表类的实例,而非类

Python内置类属性

  • dict : 类的属性(包含一个字典,由类的数据属性组成)
  • doc :类的文档字符串
  • name: 类名
  • module: 类定义所在的模块(类的全名是’main.className’,如果类位于一个导入模块mymod中,那么className.module 等于 mymod)
  • bases : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
  • 可以使用点号 . 来访问对象的属性

创建对象

#定义橄榄球运送员类
class Rugby(Athlete):
    def __init__(self,a_name,a_bod,a_squat,a_times):
        #调用父类__init__
        Athlete.__init__(self,a_name,a_bod,a_times)
        #深蹲次数
        self.squat = a_squat
    # 继承后下面两个函数就在Rugby类中,只是看不到而已
    # def top3(self):
    #     return sorted(set([self.sanitize(t) for t in self.times]))[0:3]
    # def sanitize(self,time_string):
    #     if '-' in time_string:
    #         splitter = '-'
    #     elif ':' in time_string:
    #         splitter = ':'
    #     else:
    #         return (time_string)
    #     (mins,secs) = time_string.split(splitter)
    #     return (mins+'.'+secs)

如果某个对象改变类属性会怎么样?

继承

定义:

class 子类名(父类名):

情况1,如果子类有新增的属性,那么需要在子类__init__方法中,调用父类的__init__方法

情况2,如果子类没有新增的属性,子类不需要写__init__方法

#定义橄榄球运送员类
class Rugby(Athlete):
    def __init__(self,a_name,a_bod,a_squat,a_times):
        #调用父类__init__
        Athlete.__init__(self,a_name,a_bod,a_times)
        #深蹲次数
        self.squat = a_squat
    # 继承后下面两个函数就在Rugby类中,只是看不到而已
    # def top3(self):
    #     return sorted(set([self.sanitize(t) for t in self.times]))[0:3]
    # def sanitize(self,time_string):
    #     if '-' in time_string:
    #         splitter = '-'
    #     elif ':' in time_string:
    #         splitter = ':'
    #     else:
    #         return (time_string)
    #     (mins,secs) = time_string.split(splitter)
    #     return (mins+'.'+secs)

法重写

子类方法与父类方法完全相同,子类若重写了父类的方法,则子类对象调用方法时就是调用的自己类中重新的方法。

多继承

class Father(): 
    def talk(self):
        print("---爸爸的表达能力---")

class Mather():
    def smart(self):
        print("---妈妈聪明的头脑---")

class Child(Father,Mather):
    pass

child1 = Child()
child1.talk()
child1.smart()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值