python定义一个动物类
时间: 2023-07-07 11:31:37 浏览: 86
python类定义的讲解
可以这样定义一个动物类:
```python
class Animal:
def __init__(self, name, species, sound):
self.name = name
self.species = species
self.sound = sound
def make_sound(self):
print(f"{self.name} the {self.species} says {self.sound}")
```
这个类有3个属性:`name`,`species`,`sound`,分别表示动物的名字、种类和叫声。还有一个方法`make_sound()`,用来让动物发出叫声。在创建这个类的实例时,需要传入这3个属性的值。比如:
```python
dog = Animal("Buddy", "dog", "woof")
cat = Animal("Fluffy", "cat", "meow")
dog.make_sound() # 输出:Buddy the dog says woof
cat.make_sound() # 输出:Fluffy the cat says meow
```
阅读全文