实例化一个类 - Python

时间:2016-07-28 13:12:55

标签: python class object attributeerror

我试图在Python中实例化一个简单的类。

class Student:
    def __init__(self, name, age, major, gpa):
        name = self.name
        age = self.age
        major = self.major
        gpa = self.gpa


def main():
    student_1 = Student('John', 31, 'History', 3.4)
    student_2 = Student('George', 31, 'English', 3.5)
    print student_1.name, student_2.name

我得到的错误是:

  

AttributeError:学生实例没有属性' name'

2 个答案:

答案 0 :(得分:3)

变化:

<div class="row" ng-repeat="query in prev_queries" ng-show="query.social_media.length > 0">

为:

    name = self.name
    age = self.age
    major = self.major
    gpa = self.gpa

答案 1 :(得分:1)

您收到此错误是因为您在定义属性之前访问了属性。那是因为你的分配方式是错误的 - 你试图将(未定义的)属性分配给参数而不是反过来:

def __init__(self, name, age, major, gpa):
    self.name = name
    self.age = age
    self.major = major
    self.gpa = gpa