对象是类的实例。类只是对象的蓝图。因此,鉴于您的班级定义-
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
make_student
您可以通过将属性显式分配给以下新实例来创建函数Student
-
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
但在构造函数 ( __init__
) 中执行此操作可能更有意义 -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
使用时调用构造函数Student()
。它将采用__init__
方法中定义的参数。构造函数签名现在基本上是Student(name, age, major)
.
如果你使用它,那么一个make_student
函数是微不足道的(而且是多余的) -
def make_student(name, age, major):
return Student(name, age, major)
为了好玩,这里是一个如何在make_student
不定义类的情况下创建函数的示例。请不要在家里尝试这个。
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()