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

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 = 8

blue_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 = 8

blue_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

转载于:https://blog.51cto.com/huwho/2103478

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值