在python中创建一个类的对象

时间:2016-03-11 10:33:37

标签: python

我在python中创建了一个类,为什么我会收到此错误?

class Car:

    def __init__(self, name, brand):
        self.name = name
        self.brand = brand

    def printDetails(self):
        return 'Name: ', self.name, '\nBrand: ', self.brand

    c1 = Car('A4', 'Audi')

NameError: name 'Car' is not defined

2 个答案:

答案 0 :(得分:6)

您必须在c1的之外定义Car 。修复你的缩进:

class Car:

    def __init__(self, name, brand):
        self.name = name
        self.brand = brand

    def printDetails(self):
        return 'Name: ', self.name, '\nBrand: ', self.brand

c1 = Car('A4', 'Audi')

提示:实施__str____repr__而不是printDetails

答案 1 :(得分:1)

class Car:

    def __init__(self, name, brand):
        self.name = name
        self.brand = brand

    def printDetails(self):
        return 'Name: ', self.name, '\nBrand: ', self.brand

c1 = Car('A4', 'Audi')