python的父类和子类的用法
时间: 2024-04-30 12:21:57 浏览: 148
在 Python 中,类可以通过继承来派生出子类。子类继承了父类的属性和方法,同时可以添加自己的属性和方法。下面是一个简单的例子:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
def speak(self):
return "Woof!"
class Cat(Animal):
def __init__(self, name):
super().__init__(name)
def speak(self):
return "Meow!"
dog = Dog("Buddy")
cat = Cat("Fluffy")
print(dog.name) # 输出 Buddy
print(dog.speak()) # 输出 Woof!
print(cat.name) # 输出 Fluffy
print(cat.speak()) # 输出 Meow!
```
在上面的例子中,我们定义了一个 Animal 类作为父类,其中包含一个构造函数和一个空的 speak() 方法。然后,我们定义了两个子类 Dog 和 Cat,它们都继承了 Animal 类,并且分别实现了它们自己的 speak() 方法。在子类的构造函数中,我们使用 super() 函数调用了父类的构造函数,以便子类可以继承父类的属性。
通过这个简单的例子,你可以看到如何在 Python 中定义一个父类和子类,以及如何在子类中调用父类的构造函数和方法。
阅读全文
相关推荐

















