继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

python中类的学习笔记(源码版)

别打扰我我要学习
关注TA
已关注
手记 276
粉丝 20
获赞 131

1.1第一段代码

#定义一个类(define a class )class Cat:        #属性(attribution)        #方法(methods)        def eat(self):                print("cat is eating a fish.")        def drink(slef):                print("cat is drinking milk.")        def introduce(self):                print("%s's age is %d"%(tom.chinese_name,tom.age))#创建一个对象(creating an object)tom = Cat()#调用一个对象的方法(method to invoke an object)tom.eat()tom.drink()#蠢办法添加属性(stupid method to add attributions)tom.chinese_name = "汤姆"tom.age = 18#获取对象的属性(the first way to get  properties of objects )tom.introduce()#创建多个对象,这里创建第二个对象blue_cat(create multiple objects,and the second creates bule cat)blue_cat = Cat()blue_cat.chinese_name = "蓝猫"blue_cat.age = 8blue_cat.introduce()

1.2执行第一段代码的输出

[root@localhost class]# python test.py cat is eating a fish.cat is drinking milk.汤姆's age is 18汤姆's age is 18    '''那这里我们可以看到两个不同的对象调用方法后输出了相同的结果,这就出现问题了,那怎么解决上面的问题,且看下面的代码。'''

2.1第2种方式
self的加入,解决了上面的问题。

#定义一个类(define a class )class Cat:        #属性(attribution)        #方法(methods)        def eat(self):                print("cat is eating a fish.")        def drink(slef):                print("cat is drinking milk.")        def introduce(self):                print("%s's age is %d."%(self.chinese_name,self.age))#创建一个对象(creating an object)tom = Cat()#调用一个对象的方法(method to invoke an object)tom.eat()tom.drink()#蠢办法添加属性(stupid method to add attributions)tom.chinese_name = "汤姆"tom.age = 18#获取对象的属性(the first way to get  properties of objects )tom.introduce()#创建多个对象,这里创建第二个对象blue_cat(create multiple objects,and the second creates bule cat)blue_cat = Cat()blue_cat.chinese_name = "蓝猫"blue_cat.age = 8blue_cat.introduce()

2.2第二段代码的输出

[root@localhost class]# python test.py cat is eating a fish.cat is drinking milk.汤姆's age is 18.蓝猫's age is 8.

3 init和str的使用

class Cat:        """定义了一个Cat类"""        #初始化对象        def __init__(self, new_name, new_age):                self.name = new_name                self.age = new_age        def __str__(self):            return "%s的年龄是:%d"%(self.name,self.age)        #方法        def eat(self):                print("猫在吃鱼....")        def drink(self):                print("猫正在喝牛奶.....")        def introduce(self):                print("%s的年龄是:%d"%(self.name, self.age))#创建一个对象tom = Cat("汤姆", 40)bule_cat = Cat("蓝猫", 10)print(tom)print(bule_cat)[root@localhost class]# python test2.py 汤姆的年龄是:40蓝猫的年龄是:10

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP