创建Person类,根据要求实现以下功能 (1)创建类属性count=0,每创建一个该类的对象,count的值增1 (2)定义__init__方法,实现对实例对象属性name,age的初始化,并修改count的值 (3)定义实例对象方法get返回每个人的姓名及年龄信息 (4)定义类方法get_count,输出当前Person类的实例有几个 (5)定义静态方法say_hi,返回一串文本 (6) 重新__del__方法,每次删除一个对象,实现count减一的功能 运行程序输出: my name is tom,my age is 10 there are 2 person hi,we all like python there are 1 person
时间: 2024-02-25 12:59:26 浏览: 28
以下是符合要求的Person类及运行代码:
```python
class Person:
count = 0
def __init__(self, name, age):
self.name = name
self.age = age
Person.count += 1
def get(self):
return f"my name is {self.name},my age is {self.age}"
@classmethod
def get_count(cls):
return f"there are {cls.count} person"
@staticmethod
def say_hi():
return "hi,we all like python"
def __del__(self):
Person.count -= 1
p1 = Person("tom", 10)
p2 = Person("lucy", 20)
print(p1.get())
print(Person.get_count())
print(Person.say_hi())
del p2
print(Person.get_count())
```
运行结果:
```
my name is tom,my age is 10
there are 2 person
hi,we all like python
there are 1 person
```
在这个程序中,我们创建了Person类,根据要求实现了count属性、__init__方法、get方法、get_count方法、say_hi方法和__del__方法。接着,我们创建了两个对象p1和p2,并调用了这些对象的方法。最后,我们删除了p2对象,并再次调用get_count方法,验证count属性是否正确更新。