定义一个 person 类; 在 __init__ 初始化方法中定义实例属性 height、age、name ,分别赋值为 15,15,张三; 定义一个静态方法 eat ,在方法中输出 张三在吃饭; 定义一个方法 doing ,在方法中输出我是张三,今年15岁,身高15并调用 eat 方法; 创建 person 的实例对象,并调用 doing 方法,传入 name 参数。
时间: 2024-03-10 17:46:48 浏览: 153
好的,以下是实现代码:
```python
class Person:
def __init__(self, height=15, age=15, name="张三"):
self.height = height
self.age = age
self.name = name
@staticmethod
def eat():
print("张三在吃饭")
def doing(self):
print(f"我是{self.name},今年{self.age}岁,身高{self.height}")
self.eat()
# 创建 person 实例对象,并调用 doing 方法
p = Person(name="李四")
p.doing()
```
输出结果如下:
```
我是李四,今年15岁,身高15
张三在吃饭
```
相关问题
定义一个 person 类; 在 __init__ 初始化方法中定义实例属性 height、age、name ,分别赋值为 15,15,张三; 定义一个静态方法 eat ,在方法中输出 张三在吃饭; 定义一个方法 doing ,在方法中输出我是张三,今年15岁,身高15并调用 eat 方法; 创建 person 的实例对象,并调用 doing 方法,传入 name 参数。
好的,以下是符合要求的 Python 代码:
```python
class Person:
def __init__(self, height, age, name):
self.height = height
self.age = age
self.name = name
@staticmethod
def eat():
print("张三在吃饭")
def doing(self):
print("我是{},今年{}岁,身高{}。".format(self.name, self.age, self.height))
self.eat()
# 创建实例对象并调用 doing 方法
p = Person(15, 15, "张三")
p.doing()
```
输出结果为:
```
我是张三,今年15岁,身高15。
张三在吃饭
```
TypeError: __init__() got an unexpected keyword argument 'height'
TypeError: `__init__()` 出错通常发生在尝试创建一个类实例时,传入了一个该类初始化方法`__init__`中未预期的关键字参数 'height'。Python 中的 `__init__` 方法是用来设置对象属性的构造函数,当传递了它不期望接受的参数时,就会抛出这个错误。
比如,如果你有一个只接受 'name' 和 'age' 参数的 Person 类:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
```
当你试图创建一个 Person 实例并提供额外的 'height' 参数:
```python
person = Person('Alice', 30, height=170) # 错误
```
你会得到上述的 TypeError。解决这个问题的方法是检查你的代码,确认你是否正确地按照类定义的方式传递参数,如果需要添加新的属性,应该在类的方法里处理,而不是在 `__init__` 中。
阅读全文
相关推荐
















