有父类Animal如下。设计子类Dog类和Cat类,重写__init__构造函数,给子类赋予新的名字和年龄,并调用从父类中继承的say_hello()方法,查看输出。思考子类能否访问父类中的__money和blood_type变量,利用__dict__查看三个对象所拥有的属性
时间: 2024-05-13 15:15:45 浏览: 32
```python
class Animal:
__money = 1000
blood_type = 'warm-blooded'
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"I am {self.name}, {self.age} years old.")
class Dog(Animal):
def __init__(self, name, age):
super().__init__(name, age)
self.name = 'dog ' + name
self.age = age
super().say_hello()
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name, age)
self.name = 'cat ' + name
self.age = age
super().say_hello()
a = Animal('John', 5)
d = Dog('Tom', 3)
c = Cat('Lucy', 2)
print(a.__dict__)
print(d.__dict__)
print(c.__dict__)
```
输出结果:
```
I am John, 5 years old.
I am dog Tom, 3 years old.
I am cat Lucy, 2 years old.
{'name': 'John', 'age': 5}
{'name': 'dog Tom', 'age': 3}
{'name': 'cat Lucy', 'age': 2}
```
从输出结果可以看出,子类Dog和Cat能够访问父类Animal中的继承变量blood_type,但是不能访问私有变量__money。同时,三个对象所拥有的属性分别为父类Animal中的name、age和子类中的name、age,没有其他变量。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)