please give a example about how to implement son class and father class by python
时间: 2024-06-02 15:07:08 浏览: 17
Sure, here is an example of implementing a subclass and superclass (father class) relationship in Python:
class Father:
def __init__(self, name):
self.name = name
class Son(Father):
def __init__(self, name, age):
Father.__init__(self, name)
self.age = age
father = Father("John")
son = Son("David", 20)
print(father.name)
print(son.name)
print(son.age)
In this example, Father is the superclass and Son is the subclass. The Son class inherits from the Father class using the syntax "class Son(Father):", indicating that the Son class is a subclass of the Father class.
The init function of the Son class includes both the "name" parameter from the Father class as well as a new "age" parameter specific to the Son class. It calls the init function of the Father class and passes the "name" parameter using the syntax "Father.__init__(self, name)".
When creating instances of the Father and Son classes, we can see that the Son instance has both the name attribute inherited from the Father class and the age attribute specific to the Son class.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)