类名未定义

时间:2016-06-18 05:08:55

标签: python class

class MyClass:
    sample=0
    w=0
    b=0
    g=0
    o=0
    color_list=['black','white','gray']

    def __init__(self):
        print("Enter Your Name")
        MyClass.name=input()
        print("What's the color of ur car?")
        MyClass.color=input()
        MyClass.sample=MyClass.sample+1

    def check_color(self):
        if MyClass.color in MyClass.color_list:

            if MyClass.color==MyClass.color_list[0]:
                MyClass.b=MyClass.b+1
            elif MyClass.color==MyClass.color_list[1]:
                MyClass.w=MyClass.w+1
            else:
                MyClass.g=MyClass.g+1
        else:
            MyClass.o=MyClass.o+1

    def display_result(self):
        print("Hello :",MyClass.name)
        print("Total number of black cars",MyClass.b)
        print("Total number of white cars",MyClass.w)
        print("Total number of gray cars",MyClass.g)
        print("Other cars",MyClass.o)
        print("Sample Size",MyClass.sample)

    var=0
    mylist=[]
    while var<4:
        mylist.append(MyClass())
        mylist[var].check_color()
        mylist[var].display_result()
        var=var+1

Python IDLE错误:

==== RESTART: C:/Python34/Practice Programs/TBT Tutorials/Day 4/class.py ====
Traceback (most recent call last):
  File "C:/Python34/Practice Programs/TBT Tutorials/Day 4/class.py", line 1, in <module>
    class MyClass:
  File "C:/Python34/Practice Programs/TBT Tutorials/Day 4/class.py", line 41, in MyClass
    mylist.append(MyClass())
NameError: name 'MyClass' is not defined

3 个答案:

答案 0 :(得分:0)

在您的课程中使用self而不是MyClass

答案 1 :(得分:0)

您在课堂上引用了您的课程:

class Myclass:

    ...
    mylist = []
    mylist.append(Myclass)

但是在执行您的类主体时未定义术语Myclass

似乎你混淆了缩进,应该是

class Myclass:
    ...
mylist = []
mylist.append(Myclass)

哪个会奏效。

除此之外,您应该阅读类和类的对象之间的区别,因为代码可能不是您想要的。

答案 2 :(得分:0)

问题在于缩进代码的最后一部分 - 它的方式,它是Myclass的一部分,它正在被定义,并且没有还存在!

要解决这个问题,请将其解除一个级别:

class MyClass:
    sample=0
    w=0
    b=0

    ...

        else:
            MyClass.o=MyClass.o+1

    def display_result(self):
        print("Hello :",MyClass.name)
        print("Total number of black cars",MyClass.b)
        print("Total number of white cars",MyClass.w)
        print("Total number of gray cars",MyClass.g)
        print("Other cars",MyClass.o)
        print("Sample Size",MyClass.sample)

# unindent these lines
var=0
mylist=[]
while var<4:
    mylist.append(MyClass())
    mylist[var].check_color()
    mylist[var].display_result()
    var=var+1