如何用python设计一个animal动物类?

用python设计一个animal动物类,包括颜色,属性和叫法。

class Animal:
    def __init__(self, color, attribute, sound):
        self.color = color
        self.attribute = attribute
        self.sound = sound
    
    def make_sound(self):
        print(f"The {self.attribute} {self.color} animal says '{self.sound}'")
使用方法:

# 实例化一只狗
dog = Animal("white", "cute", "bark")
# 实例化一只猫
cat = Animal("black", "sassy", "meow")

# 狗叫
dog.make_sound()  # The cute white animal says 'bark'
# 猫叫
cat.make_sound()  # The sassy black animal says 'meow'

class Animal:
    def __init__(self, color, characteristic, sound):
        self.color = color              # 定义颜色属性并赋值
        self.characteristic = characteristic  # 定义属性属性并赋值
        self.sound = sound              # 定义叫声属性并赋值
        
    def make_sound(self):
        print(f"The {self.color} animal with {self.characteristic} makes a {self.sound} sound.")
        # 输出动物颜色、属性和叫声等信息

创建一个lion对象并使用make_sound()方法输出它的信息。

lion = Animal("yellow", "a magnificent mane", "roar")   # 创建一个狮子对象
lion.make_sound()                       # 调用狮子对象的make_sound方法来输出狮子的声音和属性

创建一个bird对象并使用make_sound()方法输出它的信息。

bird = Animal("blue", "beautiful feathers", "tweet")    # 创建一个鸟对象
bird.make_sound()                       # 调用鸟对象的make_sound方法来输出鸟的声音和属性


class Animal:
    def __init__(self, color, property, call):
        self.color = color
        self.property = property
        self.call = call
    
    def show_info(self):
        print("Color: ", self.color)
        print("Property: ", self.property)
        print("Call: ", self.call)

可以这样设计一个Animal类:

class Animal:
    def __init__(self, color, attribute, sound):
        self.color = color
        self.attribute = attribute
        self.sound = sound

    def make_sound(self):
        print(self.sound)

这个类有三个属性:颜色、属性和叫声。其中,make_sound方法可以让动物发出自己的叫声。我们可以这样使用这个类:

dog = Animal('brown', 'loyal', 'woof')
cat = Animal('white', 'independent', 'meow')

print(dog.color)  # 输出:brown
print(cat.attribute)  # 输出:independent

dog.make_sound()  # 输出:woof
cat.make_sound()  # 输出:meow

这样,我们就可以创建不同的动物对象,并让它们发出自己的叫声了。