0
개인 속성을 가진 클래스를 만들려고합니다. (속성 값은 .txt 파일에서 가져옵니다.) 사용자는 속성 값을 변경할 수 있어야합니다. . 목록은 다음과 같습니다..ctxt 값을 주 기능으로 연결/변경하기
Rats
Berta/2/4/3/0
Oscar/5/0/3/2
John/-1/-6/-5/-9
내 질문은; 내 지저분한 코드는 어디서 잘못됩니까? 내가 뭘 놓치고 있니? 나는 며칠 동안 웹 검색을 해왔다.
#The class
class Rat(object):
"""Defines my class"""
def __init__(self, rat_name, sleep, joy, full, happiness):
self.__rat_name = rat_name
self.__sleep = sleep
self.__joy = joy
self.__full = full
self.__happiness = happiness
def setfull(self, value, absolute = False):
"""Gives the full attribute a value"""
try:
value = int(value)
if absolute:
self.__full = value
else:
self.__full += value
return True
except ValueError:
return False
def getfull(self):
"""Gives a fullvalue"""
return self.__full
def setfull(self, x):
x = int(x)
"""acess to the full attribute"""
self.__full = x
def sethappiness(self, value, absolute = False):
"""Gives the happiness attribute a value"""
try:
value = int(value)
if absolute:
self.__happiness = value
else:
self.__happiness += value
return True
except ValueError:
return False
def gethappiness(self):
"""Gives happiness value"""
return self.__happiness
def sethappiness(self, x):
"""access to the happiness attribute"""
x = int(x)
self.__happiness = x
def setsleep(self, value, absolute = False):
"""Gives the sleep attribute a value"""
try:
value = int(value)
if absolute:
self.__sleep = value
else:
self.__sleep += value
return True
except ValueError:
return False
def getsleep(self):
"""Gives a sleep value"""
return self.__sleep
def setsleep(self, x):
"""access to the sleep attribute"""
x = int(x)
self.__sleep = x
def setjoy(self, value, absolute = False):
"""Gives a value to the joy attribute"""
try:
value = int(value)
if absolute:
self.__joy = value
else:
self.__joy += value
return True
except ValueError:
return False
def getjoy(self):
"""Gives a joy value"""
return self.__joy
def setjoy(self, x):
"""access to the joy attribute"""
x = int(x)
self.__joy = x
# main menu functions
def cheese(self):
"""Feeds the pet"""
print("- Mmmm cheese!")
self.__full += 3
self.__sleep += 1
self.__joy += 1
return self.__full, self.__sleep, self.__joy
def play(self):
"""Plays with the rat"""
print("- Oh, I'm having fun!")
self.__full -= 2
self.__sleep += 2
self.__joy += 4
self.__happiness += 2
return self.__full, self.__sleep, self.__joy, self.__happiness
def tosleep(self):
"""Let the rat sleep"""
print("Zzzzzzz")
self.__sleep -= 7
self.__joy += 1
return self.__sleep, self.__joy
def trap(self):
"""A mousetrap"""
if self.__full > 5:
print("The rat is to full to be fooled by a simple mousetrap")
else:
print("The rat escaped with a broken tail!")
self.__joy -= 2
self.__happiness -=2
return self.__full, self.__sleep, self.__joy, self.__happiness
def __str__(self):
"""Returns a string that describes the mood of the rat"""
mood =self.rat_name + " är: "
if self.__joy > 5:
mood += "Glad, "
else:
mood += "Pissed, "
if self.__full > 8:
mood += "overfed, "
elif self.__full > 0:
mood += "full, "
elif self.__full < -5:
mood += "starving, "
else:
mood += "craving cheese and "
if self.__sleep > 7:
mood += "very tired and "
elif self.__sleep > 0:
mood += "sleepy and "
else:
mood += "well rested and "
if self.__happiness > 7:
mood += "SUPER HAPPY!"
elif self.__happiness > 0:
mood += "quite happy!"
else:
mood += "unhappy..."
return mood
# The list
def listan():
"""Opens and sorts the list"""
infil = open("ratlist.txt", "r")
infil.readline
rats = []
for row in infil:
lista = row.split("/")
print(lista)
ratname = lista[0]
ratsleep = int(lista[1])
ratjoy = int(lista[2])
ratfull = int(lista[3])
rathappiness = int(lista[4].strip())
t = Rat(ratname, ratsleep, ratjoy, ratfull, rathappiness)
rats.append(t)
print("Finished")
return rats
# the main menu
def main():
"""The menu"""
ratzinger = listan()
choice = None
while choice != "1":
print \
("""
The ratkeeper
1 - Buy a cat
2 - Listen to your rat
3 - Let the rat sleep
4 - Give the rat cheese
5 - Prepare a mousetrap
6 - Play with the rat
7 - Change the values of your rat
8 - Know the name of my rat
""")
choice = input("I want to: ")
if val == "1":
print(rat_name, "was tortured and eaten, bye.")
elif val == "2":
print(ratzinger)
elif val == "3":
ratzinger.tosleep()
elif val == "4":
ratzinger.cheese()
elif val == "5":
ratzinger.trap()
elif val == "6":
ratzinger.play()
elif val == "7":
print()
elif val == "8":
print()
else:
print("Choose a number between one and eight!")
main()
input()
이것은 다른 언어에서 파이썬 구문으로의 음역처럼 읽습니다. (우리 중 얼마나 많은 사람들이 먼저 시작했는지 걱정하지 마십시오.) 코드를 실제로 실행시키기 위해서는'infil .readline'을'infil.readline()'으로 바꾸면, 메소드가 실제로 호출되어 데이터 파일의 첫 번째 줄을 건너 뛰고 입력 변수'choice' 나'val'을 호출 할 것인지 결정해야합니다. . 그러면 루프가 생겨서 파이썬에서 다시 작성할 수 있습니다. – DSM
(아, 거의 잊었 : 내가 "Form"을 수정하기 위해 편집했을 때 "Class"를 "SyntaxError"가 주어지기 때문에 "Class"로 변경했다. 나는 게시 프로세스 중에 대문자 C가 도입되었다고 가정하고있다.) – DSM