在main函数中连接和更改.txtvalues

2024-05-15 04:06:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个具有私有属性的类(attributeValue是从.txt文件导入的),用户应该能够更改属性的值。列表如下所示:

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()

Tags: theselfreturnifvaluedefsleepfull
1条回答
网友
1楼 · 发布于 2024-05-15 04:06:06

除了上面的答案:Python中的双下划线并不意味着标记的属性是私有的。双下划线应用名称混乱,用于避免命名冲突。如果你的意思是“私人”,那么你应该用一个下划线

相关问题 更多 >

    热门问题