class MyCar: steer_shape='rectangle' __weight=3000 def init(self,n_wheel,n_sits): self.n_wheel=n_wheel self.n_sits=n_sits def run(self): print("The car has already started") print(MyCar.dict) print(MyCar._MyCar__weight) mycar=MyCar(4,5) mycar.run() 在上例基础上,通过mycar采用两种不同方法访问属性 n_wheel
时间: 2024-03-10 10:47:21 浏览: 17
可以通过以下两种方法访问属性 n_wheel:
1. 直接使用实例对象 mycar.n_wheel,如下所示:
```python
print(mycar.n_wheel)
```
2. 使用类对象 MyCar 和属性名 n_wheel,通过类访问实例属性,如下所示:
```python
print(MyCar.n_wheel.__get__(mycar))
```
这两种方法都可以访问到实例属性 n_wheel 的值。
相关问题
定义一个汽车类MyCar,要求MyCar具有一个静态属性 steer_shape描述方向盘的形状,如方形(rectangle)或圆形(circle); 具有一个静态私有属性 weight描述车的重量;要求其实例化对象具有属性 n_wheel, n_sits 分别表示车轮个数和座位数;要求MyCar类拥有方法run(方法具体内容可自行设计)。(10分) 要求打印出类MyCar的全部属性,输出私有属性weight的值;假如mycar为类MyCar的一个实例化对象,打印出mycar的全部属性,并调用方法run.
代码如下:
```python
class MyCar:
steer_shape = 'circle'
__weight = 1000
def __init__(self, n_wheel, n_sits):
self.n_wheel = n_wheel
self.n_sits = n_sits
def run(self):
print("The car is running.")
def print_all_attributes(self):
print("steer_shape:", MyCar.steer_shape)
print("weight:", MyCar.__weight)
print("n_wheel:", self.n_wheel)
print("n_sits:", self.n_sits)
my_car = MyCar(4, 5)
my_car.print_all_attributes()
my_car.run()
```
输出结果为:
```
steer_shape: circle
weight: 1000
n_wheel: 4
n_sits: 5
The car is running.
```
3. 在上例基础上,通过mycar采用两种不同方法访问属性 n_wheel
可以使用以下两种方法访问属性 `n_wheel`:
方法一:使用点操作符
```python
class Car:
def __init__(self, n_wheel):
self.n_wheel = n_wheel
mycar = Car(4)
print(mycar.n_wheel) # 输出 4
```
方法二:使用 getattr() 函数
```python
class Car:
def __init__(self, n_wheel):
self.n_wheel = n_wheel
mycar = Car(4)
print(getattr(mycar, 'n_wheel')) # 输出 4
```