Python, creating objects

前端 未结 4 1022
旧巷少年郎
旧巷少年郎 2020-12-04 07:04

I\'m trying to learn python and I now I am trying to get the hang of classes and how to manipulate them with instances.

I can\'t seem to understand this practice pro

4条回答
  •  不知归路
    2020-12-04 07:39

    Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -

    # Note the added (object) - this is the preferred way of creating new classes
    class Student(object):
        name = "Unknown name"
        age = 0
        major = "Unknown major"
    

    You can create a make_student function by explicitly assigning the attributes to a new instance of Student -

    def make_student(name, age, major):
        student = Student()
        student.name = name
        student.age = age
        student.major = major
        return student
    

    But it probably makes more sense to do this in a constructor (__init__) -

    class Student(object):
        def __init__(self, name="Unknown name", age=0, major="Unknown major"):
            self.name = name
            self.age = age
            self.major = major
    

    The constructor is called when you use Student(). It will take the arguments defined in the __init__ method. The constructor signature would now essentially be Student(name, age, major).

    If you use that, then a make_student function is trivial (and superfluous) -

    def make_student(name, age, major):
        return Student(name, age, major)
    

    For fun, here is an example of how to create a make_student function without defining a class. Please do not try this at home.

    def make_student(name, age, major):
        return type('Student', (object,),
                    {'name': name, 'age': age, 'major': major})()
    

提交回复
热议问题