创建一个学生类(name,sex,clazz),请分别使用静态工厂实例化、实例工厂完成实例化。通过set方式,完成对他们参数的注入。并对这几种方法进行测试。 并测试输出(在测试方法中请提示“测试方法”。如提示“构造方法注入,实例化内容:student(name:张三 ,sex:女,clazz:150704”)。
时间: 2023-04-27 14:02:14 浏览: 167
创建学生(Student)类,并实例化对象访问测试
5星 · 资源好评率100%
静态工厂实例化:
```
class Student:
def __init__(self, name, sex, clazz):
self.name = name
self.sex = sex
self.clazz = clazz
@staticmethod
def create_student(name, sex, clazz):
return Student(name, sex, clazz)
# 测试静态工厂实例化
def test_static_factory_init():
print("测试静态工厂实例化:")
student = Student.create_student("张三", "女", "150704")
print("实例化内容:student(name: %s, sex: %s, clazz: %s)" % (student.name, student.sex, student.clazz))
test_static_factory_init()
```
实例工厂实例化:
```
class Student:
def __init__(self):
self.name = None
self.sex = None
self.clazz = None
def set_name(self, name):
self.name = name
def set_sex(self, sex):
self.sex = sex
def set_clazz(self, clazz):
self.clazz = clazz
def create_student(self, name, sex, clazz):
self.set_name(name)
self.set_sex(sex)
self.set_clazz(clazz)
return self
# 测试实例工厂实例化
def test_instance_factory_init():
print("测试实例工厂实例化:")
student = Student().create_student("李四", "男", "150705")
print("实例化内容:student(name: %s, sex: %s, clazz: %s)" % (student.name, student.sex, student.clazz))
test_instance_factory_init()
```
通过set方式注入参数:
```
class Student:
def __init__(self):
self.name = None
self.sex = None
self.clazz = None
def set_name(self, name):
self.name = name
def set_sex(self, sex):
self.sex = sex
def set_clazz(self, clazz):
self.clazz = clazz
# 测试set注入
def test_set_injection():
print("测试set注入:")
student = Student()
student.set_name("王五")
student.set_sex("男")
student.set_clazz("150706")
print("实例化内容:student(name: %s, sex: %s, clazz: %s)" % (student.name, student.sex, student.clazz))
test_set_injection()
```
上面代码中,静态工厂实例化使用了静态方法create_student,通过调用类名.create_student()来实例化对象。实例工厂实例化使用了create_student方法,通过对象.create_student()来实例化对象。set方式注入使用了set_name, set_sex, set_clazz方法,通过对象.set_name("xxx")来设置对象属性。
阅读全文