2017-08-10 36 views
0

我无法创建一个类Animal的对象。如果我这样做,当#FILE I/0代码被注释掉时,它会给我一个错误,说明“Unresolved reference Animal”。 如果它不是,那么它会给我错误,如图所示。 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()) 
+0

打开任务管理器并检查某个进程是否正在使用test.txt。 – CunivL

+0

请考虑制作一个最小的完整和可验证的示例:https://stackoverflow.com/help/mcve。您分享的代码非常长,很多事情与问题无关。 – FunkySayu

回答

0

这是一个缩进问题。您正在类中创建Aninal类的实例。最后两行代表在班上。

+0

谢谢!对象被制成。 –

+0

但是如果我取消注释文件I/O部分,仍然存在“Traceback”的错误。 –

+0

您正在将两个参数传递给bytes contstructor bytes(“将我写入文件\ n”,“UTF-8”)。它只需要一个字节(“将我写入文件\ n”) –

相关问题