为什么我会收到一个Traceback(最近一次调用最后一次):

时间:2017-08-10 10:57:58

标签: python compiler-errors traceback

我无法创建Animal类的对象。如果我这样做,它会给我一个错误说"未解决的参考动物"当#FILE I / 0代码被注释掉时。 如果它不是那么它会给我错误,如图所示。 Traceback most recent call: last error 有人可以帮我解决这个问题吗?我正在制作这个完整的文件,以便我可以涵盖PYTHON的基本语法。

import random
import sys
import os
import math

#SIMPLE THINGS AND MATHS
print("STARTING SIMPLE THINGS AND MATHS!!!")
print("Hello World")  #This is a code for printing hello world

#Comment

"""
This
is a
multiline
comment
"""


name = "Derek"
y="2"
print (y)
print(name)

#Numbers Strings List Tuples Dictionaries
#+ - * / % ** //

name=15
print(name)
print("5 + 2 =",5+2)
print("5 - 2 =",5-2)
print("5 * 2 =",5*2)
print("5 / 2 =",5/2)
print("5 % 2 =",5%2)
print("5 ** 2 =",5**2)
print("5 // 2 =",5//2)

print("1 + 2 - 3 * 2 =", 1 + 2 - 3 * 2)
print("(1 + 2 - 3) * 2 =", (1 + 2 - 3) * 2)

quote = "\"Always remember you are unique\""
print("Single line quote: ",quote)

multi_line_quote = "\"""""Just
like everyone else""""\""
print("Multi Line quote: ",multi_line_quote)
print("%s %s %s" %('I like the quote', quote, multi_line_quote))
print("I dont like ",end="")
print("newlines")
print('\n'*5)



print("LISTS!!!")
#LISTS
grocery_list = ['Juice','Tomatoes','Potatoes',
                'Bananas']
print('First item: ',grocery_list[0])

grocery_list[0] = "Green Juice"
print('First item: ',grocery_list[0])

print(grocery_list[1:3])

other_events=['Wash Car', 'Pick Up Kids','Cash Check']

to_do_list = [other_events, grocery_list] #list within a list
print(to_do_list[1][1])   #2nd item of second list

grocery_list.append('Onions')
print(to_do_list)

grocery_list.insert(1,"Pickle")  #Inserting item on second index
print(to_do_list)

grocery_list.remove("Pickle")     #Removing pickle from grocery list
print(to_do_list)

grocery_list.sort()     #Sorting grocery list alphabetically
print(to_do_list)

grocery_list.reverse()  #Sorting grocery list in reverse order albhabetically
print(to_do_list)

del grocery_list[4]     #Delete item from grocery list which is on index 4
print(to_do_list)

to_do_list2 = other_events + grocery_list
print(len(to_do_list2))
print(max(to_do_list2))  #Whatever comes last alphabetically
print(min(to_do_list2))  #Whatever comes first alphabetically

to_do_list2.insert(1,"Bananas")
print(min(to_do_list2))
print("\n"*5)




#Tuples
print("TUPLES!!!")
pi_tuple=(3,1,4,1,5,9)
new_tuple=list(pi_tuple)    #Converting tuple to list
new_list=tuple(new_tuple)   #Converting list to tuple
print(len(new_list))
print(max(new_list))
print(min(new_list))
print("\n"*5)




#Dictionaries
print("DICTIONARIES!!!")
super_villains={'Fiddler':'Isaac Bowin',
                'Captain Cold': 'Leonard Snart',
                'Weather Wizard': 'Mark Mardon',
                'Mirror Master': 'Sam Scudder',
                'Pied Piper':'Thomas Peterson'}
print(super_villains['Captain Cold'])
print(len(super_villains))
del super_villains['Fiddler']
super_villains['Pied Piper']='Hartley Rathway'
print(len(super_villains))
print(super_villains.get("Pied Piper"))
print(super_villains.keys())
print(super_villains.values())
print("\n"*5)




#IF ElSE ELIF == != > >= < <=
print("IF ElSE ELIF (== != > >= < <=)")
age=21
if age>16:
    print("You are old enough to drive")
else:
    print("You are not old enough to drive")

if age>=21:
    print("You are old enough to drive a tractor trailer")
elif age>=16:
    print("You are old enoguh to drive a car")
else:
    print("You are not old enough to drive")
#LOGICAL OPERATORS (AND OR NOT)
age=30
if ((age>=1) and (age<=18)):
    print("You get a birthday")
elif (age==21)or(age>=65):
    print("You get a birthday")
elif not(age==30):
    print("You don't get a birthday")
else:
    print("You get a birthday party yeah")
print("\n"*5)





#LOOPS
print("LOOPS!!!")
print('\n')
print("FOR LOOPS!!!")


for x in range(0,10):
    print(x,' ',end="")
print('\n')

grocery_list=['Juice','Tomatoes','Potatoes','Bananas']
for y in grocery_list:
    print(y)

for x in [2,4,6,8,10]:
    print(x)
print('\n')
num_list=[[1,2,3],[10,20,30],[100,200,300]]
for x in range(0,3):
    for y in range(0,3):
        print(num_list[x][y])
print('\n'*2)

print("WHILE LOOPS!!!")
random_num= random.randrange(0,16)   #Generates a random number between 0 to 99
while(random_num!=15):
    print(random_num)
    random_num=random.randrange(0,16)
print('\n')

i=0;
while(i<=20):
    if(i==0):
        i += 1
        continue
    elif(i%2==0):
        print(i)
    elif(i==9):
        break
    else:
        i+=1    #i=i+1
        continue
    i+=1

print('\n')
print('Finding prime numbers')
#FINDING PRIME NUMBERS BETWEEN 0 AND 20
max_num = 20

primes = [2]  # start with 2
test_num = 3  # which means testing starts with 3

while test_num < max_num:
    i = 0
    # It's only necessary to check with the primes smaller than the square
    # root of the test_num
    while primes[i] <= math.sqrt(test_num):
        # using modulo to figure out if test_num is prime or not
        if (test_num % primes[i]) == 0:
            test_num += 1
            break
        else:
            i += 1
    else:
        primes.append(test_num)
        test_num += 1

print(primes)
print('\n'*5)




#FUNCTIONS
print("FUNCTIONS")
def sum(fNum,lNum):
    sumNum = fNum+lNum
    return sumNum

sum_of_two = sum(1,2)
print(sum_of_two)
print("The sum of 1 and 2 is: ",sum(1,2))
print('\n'*5)



#TAKE INPUT FROM USER
print("TAKE INPUT FROM USER!!!")
print("What is your name: ")
#name = sys.stdin.readline()
#print("Hello ",name)
print('\n'*5)



#STRINGS
print("STRINGS!!!")
long_string="i'll catch you if you fall - The Floor"
print(long_string[0:4])
print(long_string[-5:])
print(long_string[:-5])
print(long_string[:4] + " be there")
print("%c is my %s letter and my number %d number is %.5f" %
      ('X','favorite',1,.14))
print(long_string.capitalize())  #Capitalizes first letter of the string
print(long_string.find("Floor"))
print(long_string.isalpha())
print(long_string.isalnum())
print(len(long_string))
print(long_string.replace("Floor","Ground"))
print(long_string.strip())  #Strip white space
quote_list = long_string.split(" ")
print(quote_list)
print('\n'*5)



#FILE I/0
print("FILE I/0!!!")
test_file = open("test.txt","wb")      #Opens the files in write mode
print(test_file.mode)
print(test_file.name)
test_file.write(bytes("Write me to the file\n", 'UTF-8'))   #Writes to the file
test_file.close()
test_file = open("test.txt","r+")
text_in_file = test_file.read()
print(text_in_file)
os.remove("test.txt")  #Deletes the file
print('\n'*5)




#OBJECTS
print("OBJECTS!!!")
class Animal:
    __name = None   #or __name = ""
    __height = 0
    __weight = 0
    __sound = 0

    def __init__(self,name,height,weight,sound):
        self.__name = name
        self.__height = height
        self.__weight = weight
        self.__sound = sound


    def set_name(self, name):
        self.__name = name

    def set_height(self, height):
        self.__height = height

    def set_weight(self, weight):
        self.__weight = weight

    def set_sound(self, sound):
        self.__sound = sound

    def get_name(self):
        return self.__name

    def get_height(self):
        return str(self.__height)

    def get_weight(self):
        return str(self.__weight)

    def get_sound(self):
        return self.__sound

    def get_type(self):
        print("Animal")

    def toString(self):
        return "{} is {} cm tall and {} kilograms and say {}".format(self.__name,
                                                                     self.__height,
                                                                     self.__weight,
                                                                     self.__sound)
    cat = Animal('Whiskers',33,10,'Meow')
    print(cat.toString())

1 个答案:

答案 0 :(得分:0)

这是一个缩进问题。您正在类中创建Aninal类的实例。在课堂上排除最后两行。

相关问题