码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-04-14 19:07:16      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:类的使用

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

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

标签:类的使用

原文地址:http://blog.51cto.com/huwho/2103478

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!