【组队学习】Task07:面向对象的编程

面向对象的编程

Python 是一门“面向对象的编程语言”。

这指python中有一个叫做类(class)的结构,能以特定的方式结构化你的软件。

(一)类的例子

class song(object):  #创建类,song为类的名字
    
    def __init__(self,lyrics):  #def与__之间要有空格,否则出错
        self.lyrics=lyrics
        
        
    def sing_me_a_song(self):      #定义函数
        for line in self.lyrics:   #通过循环,遍历每一句歌词
            print(line)
            
happy_bday=song(["Happy birthday to you",     #()为元组,[]为列表,元组里嵌套列表
                 "I don't want to get sued",
                 "So I'll stop right there"])

bulls_on_parade=song(["They rally around the family",
                      "With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
Happy birthday to you
I don't want to get sued
So I'll stop right there
They rally around the family
With pockets full of shells
class belong(object):
    
    def __init__(my,ly):
        my.ly=ly
        
    
    def you_belong_to_me(my):
        for line in my.ly:
            print(line)
            
you_belong_to_me_1=belong(["See the pyramids along the Nile",
                          "Watch the sun rise from the tropic isle",
                           "Just remember darling all the while",
                          "You belong to me"])
#歌词为电影《怪物史莱克》插曲you belong to me
you_belong_to_me_2=belong(["See the market place in old Algiers",
                          "Send me photographs and souvenirs",
                          "Just remember when a dream appears",
                          "You belong to me"])
you_belong_to_me_1.you_belong_to_me()
you_belong_to_me_2.you_belong_to_me()
See the pyramids along the Nile
Watch the sun rise from the tropic isle
Just remember darling all the while
You belong to me
See the market place in old Algiers
Send me photographs and souvenirs
Just remember when a dream appears
You belong to me

(二)学着去说面向对象

词汇训练

类(class):告诉Python创建一个新类型的东西

对象(object):一是表示最基本类型的东西,二是表示任何实例

实例(instance):当你告诉python创建一个类的时候你所得到的东西

def:在类里面定义一个函数

self:在一个类的函数里面,self是被访问的实例/对象的一个变量

继承(inheritance):一个类能从另一个类那继承它的特征概念

组合(composition):一个类可以由其他一些类构成的概念

属性(attribute):类所拥有的从组合那里得到的特性,通常为变量

is-a:一种来表达某物继承自一种东西的表述

has-a:一种用来表达某物是由一些东西组成或具有某种特性的表述

短语训练

一些Python 代码片段以及右边的解释

class X(Y):

创建一个名为X并继承自Y的类

class X(object):def init(self,J)

类X有一个带有self和J参数的init函数

class X(object):def M(self,J):

类X有一个带有self和J参数的M函数

foo=X():

设foo为类X的一个实例

foo.M(J)

从foo那里获取M函数,并用self和J参数来调用它

foo.K=Q

从foo那里获取K属性,并设它为Q

参考datawhale组队学习教程第7章:

学习教程详见《零基础学Python编程思维》教程

【教程地址】https://linklearner.com/datawhale-homepage/index.html#/learn/detail/6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值