python初级(302) 6 对象(二)

一、复习

1、什么是对象

2、什么是类

3、什么是属性

4、什么是方法

5、创建一个dog类,dog的属性有颜色,方法有汪汪叫

随堂练习:

class Dog:
    def __init__(self, color):
        self.color = color

    def wangwang(self):
        print("Dog wangwang!")


dog = Dog("white")
dog.wangwang()

6、创建一个cat类,cat的属性有拥有老鼠的只数,方法有捉老鼠

class Cat:
    def __init__(self, mouse_count):
        self.mouse_count = mouse_count

    def catch_mouse(self):
        self.mouse_count += 1
        print("Cat has mouse count:", self.mouse_count)

    def __str__(self):
        text = "Cat has {} mouse.".format(self.mouse_count)
        return text


cat = Cat(0)
cat.catch_mouse()
cat.catch_mouse()
print(cat)

二、魔法方法

前面学过一个魔法方法,__init__(),该方法会在对象创建时完成初始化。每个对象内置一个__init__()方法。如果你在类定义中没有加入自己的__init__()方法,就会有这样一个内置方法接管,它的工作就是创建对象。

另一个特殊方法是__str__(),它会告诉Python打印(print)一个对象时具体显示什么内容。

主要打印如下内容:

1、实例在哪里定义

2、类名

3、存储实例的内存位置(0x00BB83A0部分)

不过,也可以定义自己的__str__(),这会覆盖内置的__str__()方法

def __str__(self):
        text = "Cat has {} mouse.".format(self.mouse_count)
        return text

三、练习

1、创建一个dog对象,此对象是白色的狗,名字叫贝贝,有10岁了,如果写出语句:

print(dog), 显示为:Dog name is Beibei,has 10 old.

它会汪汪叫,也会跑。

2、创建一个cat对象,此对象是白色的猫,有3岁了,刚创建时它没有老鼠,不过它会捉老鼠,还会跑,也会吃老鼠

如果写出语句:print(cat),显示为:Cat has 3 old,has 2 mouses.(假设创建猫以后,它已经捉了两次老鼠了并且还没开始吃)

原文地址:https://www.cnblogs.com/luhouxiang/p/11828913.html