写一个子类继承父类的代码
时间: 2023-12-01 13:58:49 浏览: 34
Sure, here's an example code of a subclass inheriting from the parent class:
```
class ParentClass:
def __init__(self, x, y):
self.x = x
self.y = y
def print_values(self):
print("x:", self.x)
print("y:", self.y)
class ChildClass(ParentClass):
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
def print_values(self):
super().print_values()
print("z:", self.z)
child_obj = ChildClass(1, 2, 3)
child_obj.print_values()
```
In this example, `ChildClass` is the subclass and `ParentClass` is the parent class. `ChildClass` inherits from `ParentClass` by using the syntax `class ChildClass(ParentClass):`. The `super().__init__(x, y)` call in the `ChildClass.__init__()` function calls the `ParentClass.__init__()` function to set the values of `x` and `y`.
After that, `ChildClass` defines its own value `z` and overrides the `ParentClass` method `print_values()` to print all three values. Finally, an instance of `ChildClass` is created and its `print_values()` method is called to output all three values.
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)