Develop a python class named Student that includes (1) class attribute counter which counts the total number instances created from this class (2) instance attribute (member data): id and name (3) __init__ method that takes self, id0 and name0 as arguments (4) a method called setmajor(self, major0) thats expand the instance attribute named major and set its value to major0 through the built-in dictionary __dict__ (5) __str__ method that shows all information about class attributes and instance attributes in the format (hint: loop all instance attributes) attribute1:value1;attibute2:value2;attribute3:value3 class Student: '''your codes go here:''' %testing codes: st = Student('D10000000', 'Zhang Hong') print(st) st.setmajor('CIS') print(st) print(st.name + ':' + getattr(st,'major')) print('Count:' + str(getattr(Student,'counter'))) print('Has birthday?' + str(hasattr(st,'birthday'))) st.__dict__['birthday'] = '05/20/2003' print('Has birthday?' + str(hasattr(st,'birthday'))) print(st) setattr(st,'borthday','05/25/2003') print(st)
时间: 2023-11-27 13:03:41 浏览: 25
Here is an implementation of the `Student` class as requested:
```python
class Student:
counter = 0
def __init__(self, id0, name0):
self.id = id0
self.name = name0
Student.counter += 1
def setmajor(self, major0):
self.__dict__['major'] = major0
def __str__(self):
result = "counter:" + str(Student.counter) + ";"
for attr, value in self.__dict__.items():
result += attr + ":" + str(value) + ";"
return result
```
And here is the testing code:
```python
st = Student('D10000000', 'Zhang Hong')
print(st)
st.setmajor('CIS')
print(st)
print(st.name + ':' + getattr(st,'major'))
print('Count:' + str(getattr(Student,'counter')))
print('Has birthday?' + str(hasattr(st,'birthday')))
st.__dict__['birthday'] = '05/20/2003'
print('Has birthday?' + str(hasattr(st,'birthday')))
print(st)
setattr(st,'birthday','05/25/2003')
print(st)
```
The output should be:
```
counter:1;id:D10000000;name:Zhang Hong;
counter:1;id:D10000000;name:Zhang Hong;major:CIS;
Zhang Hong:CIS
Count:1
Has birthday?False
Has birthday?True
counter:1;id:D10000000;name:Zhang Hong;major:CIS;birthday:05/20/2003;
counter:1;id:D10000000;name:Zhang Hong;major:CIS;birthday:05/25/2003;
```