判断题:对于以下类定义: ```python class Student(): cls_teacher = 'Macdonald' cls_teacher = 'Linda' def __init__(self,name,age): self.name = name # 用于自我介绍的函数 def intro(self): print(f'My name is {self.name}.') ``` 以下代码能够正常运行 ``` a = Student('Alice',21) b = Student('Bob',20) b.nickname = a.nickname = "Ali" del a.nickname print(b.nickname) ```
时间: 2023-12-16 14:03:23 浏览: 69
错误。
因为在类定义中没有定义`nickname`属性,所以在给`a`和`b`对象分别赋值时会报错。如果要给`a`和`b`对象添加`nickname`属性,则需要在`__init__`方法中添加`self.nickname`属性的定义,如下:
```python
class Student():
cls_teacher = 'Macdonald'
cls_teacher = 'Linda'
def __init__(self,name,age):
self.name = name
self.nickname = None # 添加nickname属性的定义
# 用于自我介绍的函数
def intro(self):
print(f'My name is {self.name}.')
```
然后,以下代码才能正常运行:
```python
a = Student('Alice',21)
b = Student('Bob',20)
b.nickname = a.nickname = "Ali"
del a.nickname
print(b.nickname) # 输出:Ali
```
阅读全文