Python类Setter不改变变量

时间:2017-04-08 21:07:51

标签: python

我能找到的最接近我的问题的主题是:Python setter does not change variable

它没有真正帮助,音量和频道根本没有变化。 “看电视”的第一个功能完全正常。

class TV(object):

    def __init__(self, channel, volume):
        self.__channel = channel
        self.__volume = volume

    def __str__(self):
        out = ""
        out += "You're on channel #" + str(self.__channel) + ", " +     self.channelNetwork()
    out += "\nVolume is currently at: " + str(self.__volume) + "/20"
    return out

# a method that determines the name for each channel from 1-10

def channelNetwork(self):
    c = self.__channel
    if c == 1:
        return "CBS"
    elif c==2:
        return "NBC"
    elif c==3:
        return "ABC"
    elif c==4:
        return "Fox"
    elif c==5:
        return "ESPN"
    elif c==6:
        return "PBS"
    elif c==7:
        return "CNN"
    elif c==8:
        return "Comedy Central"
    elif c==9:
        return "Cartoon Network"
    elif c==10:
        return "Nicklodeon"

# a volume slider that has a range from 0-20

def volumeSlider(self, newVolume):
    v = self.__volume
    if newVolume == "+":
        v += 1
    else:
        v -= 1
    if v < 0:
        v = 0
    if v > 20:
        v = 20

def channelChanger(self, newChannel):
    c = self.__channel
    if newChannel == "+":
        c += 1
    else:
        c -= 1
    if c < 0:
        c = 0
    if c > 10:
        c = 10

def main():
import random
randomChannel = random.randint(1,10)
randomVolume = random.randrange(21)
televsion = TV(randomChannel, randomVolume)

choice = None
while choice != "0":
    print \
    ("""
    TV Simulator

    0 - Turn off TV
    1 - Watch TV
    2 - Change channel
    3 - Change volume
    """)

    choice = input("Choice: ")
    print()

    # exit
    if choice == "0":
        print("Have a good day! :)")

    elif choice == "1":
        print("You relax on your couch and watch some TV")
        print(televsion)

    elif choice == "2":
        newChannel = None
        while newChannel not in ('+', '-'):
            newChannel = input("\nPress '+' to go up a channel and press '-' to go down a channel: ")
        televsion.channelChanger(newChannel)

    elif choice == "3":
        newVolume = None
        while newVolume not in ('+', '-'):
            newVolume = input("\nPress '+' to increase volume and press '-' to decrease volume: ")
        televsion.volumeSlider(newVolume)

    else:
        print("\nSorry, but", choice, "isn't a valid choice.")

main()
input("\n\nPress enter to exit.")

1 个答案:

答案 0 :(得分:3)

问题是,当你这样做时:

def volumeSlider(self, newVolume):
    v = self.__volume
    if newVolume == "+":
        v += 1
    else:
        v -= 1
    if v < 0:
        v = 0
    if v > 20:
        v = 20

在:

v

分配给self.__volume不会影响self.__volume = 20。您需要使用self.volume或其他任何内容。

顺便说一句,除非你真的需要,否则不要使用双下划线名称修改。例如。 type="textt"没问题。