Python, creating objects

前端 未结 4 1012
旧巷少年郎
旧巷少年郎 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 08:03

    Create a class and give it an __init__ method:

    class Student:
        def __init__(self, name, age, major):
            self.name = name
            self.age = age
            self.major = major
    
        def is_old(self):
            return self.age > 100
    

    Now, you can initialize an instance of the Student class:

    >>> s = Student('John', 88, None)
    >>> s.name
        'John'
    >>> s.age
        88
    

    Although I'm not sure why you need a make_student student function if it does the same thing as Student.__init__.

提交回复
热议问题