Python的类

类的定义

class Human(object):
    def eat(self):
        print('I can eat')
DoctorLiu = Human()
DoctorLiu.eat()
I can eat
  • class Human(object)定义一个类叫做Human,Human类继承了object这个类,object类是python内的一个基础类,所有的类都继承它
  • def eat(self)定义了一个函数叫做eat,他的作用是输出一句话:I can eat,self作为一个参数传入,self为类本身(实际为实例化之后的类,即为DoctorLiu),self传入时,会将这个类所有的变量传入,目前未给self定义其他变量。

类的函数的传参

class Human(object):

    def eat(self,food=None):
        if food:
            print('I like eating %s'%food)
        else:
            print('I can eat')

DoctorLiu = Human()
DoctorLiu.eat()
DoctorLiu.eat('shrimp')
I can eat
I like eating shrimp
  • 定义了一个函数叫做eat,参数food的默认值为None,if food 表示,若food不为None时,则该表达式为真,则输出:’I like eat %s’%food,%s为占位符,即先占据一个位置,用food的值来填充它。若 food 为None,则输出:I can eat。

self的使用

class Human(object):

    def eat(self,food=None):
        if food:
            like_food = food
            self.LIKE_FOOD = food
            print('I like eating %s'%self.LIKE_FOOD)
            print('I like eating %s' % like_food)
        else:
            print('I can eat')
    def Question(self):
        print('You like eating %s'%self.LIKE_FOOD)
        #print('You like %s'%like_food)

DoctorLiu = Human()
DoctorLiu.eat()
DoctorLiu.eat('shrimp')
DoctorLiu.Question()
print(DoctorLiu.LIKE_FOOD)
I can eat
I like eating shrimp
I like eating shrimp
You like eating shrimp
shrimp
  • 在eat函数中,将food赋值给self.like_food,虽然这个赋值语句发生在eat这个函数内,但由于self的存在,self.like_food成为Human这一整个类的变量,他不仅可以在eat函数里面使用,也可以在Human这个类的其他函数里面直接使用,而like_food只能在eat这个函数内使用。

  • 在Question函数中,若执行print(‘You like %s’%like_food)将会报错,因为like_food只属于eat这个函数,而self.LIKE_FOOD属于Human这个类,所以Human的任何函数都可以直接调用它

  • LIKE_FOOD已经成为DoctorLiu这个类的一部分,可以认为是DoctorLiu的一个属性,可以直接输出来看看,而like_food却不可以

__init__的使用

class Human(object):

    def __init__(self):
        self.num_hands=2
        self.num_legs=2

DoctorLiu = Human()
print("DoctorLiu有%s只手"%DoctorLiu.num_hands)
print("DoctorLiu有%s条腿"%DoctorLiu.num_legs)
DoctorLiu有2只手
DoctorLiu有2条腿
  • 一个实例在创建时,会有一些自身所带有的变量,不需要在通过调用其他函数而获得,如Human是一个类型,而DoctorLiu是Human一个实例,DoctorLiu在被创建时,她自身就会有两条腿,两只手,这个属性是不需要后天去学习而获得,是与生俱来的。

  • 而上一段代码中self.LIKE_FOOD,需要去执行eat这个函数,DoctorLiu才有了这个属性。

__init__传参

class Human(object):

    def __init__(self,eyes,skin):
        self.num_hands=2
        self.num_legs=2
        self.eyes = eyes
        self.skin = skin

DoctorLiu = Human(eyes='大',skin='白')
print("DoctorLiu有%s只手"%DoctorLiu.num_hands)
print("DoctorLiu有%s条腿"%DoctorLiu.num_legs)
print("DoctorLiu有%s眼睛"%DoctorLiu.eyes)
print("DoctorLiu有%s皮肤"%DoctorLiu.skin)
DoctorLiu有2只手
DoctorLiu有2条腿
DoctorLiu有大眼睛
DoctorLiu有白皮肤
  • 实例在创建的过程中,也可以对它进行赋值,和普通函数的赋值过程是一样的。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值