更新:在Python中调用Class方法时设置参数

时间:2018-04-22 10:08:02

标签: python python-3.x

我制作了这个简单的程序来模拟一个广播电台。我需要弄清楚如何根据当前电台的设置来设置预设。

以下是菜单选项:

print("\n1 = Display tuned in station")
print("2 = Program preset station 1")
print("3 = Program preset station 2")
print("4 = Program preset station 3")
print("5 = Seek next station")
print("6 = Tune preset station 1")
print("7 = Tune preset station 2")
print("8 = Tune preset station 3")
print("9 = Dump Programming")
print("10 = Turn off radio")

当您选择“5”时,无线电搜索到下一个电台。这样做是CLASS METHOD [def seekNext(self):]

所以我需要帮助,如何使用CLASS METHOD [def longPressPreset1 through3(self):]选择选项“2,3和4”时将当前电台设置为预设?

在设置预设后,如何使用CLASS METHOD [def shortPressPreset1 through3(self):]显示预设?

class Radio:

def __init__(self):
    self.stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
    self.station_index = 0
    self.current = self.stations[0]
    self.preset = 0
    self.presetStation1 = self.stations[0]
    self.presetStation2 = self.stations[0]
    self.presetStation3 = self.stations[0]

def seekNext(self):
    self.stations[self.station_index]
    self.station_index = (self.station_index + 1) % len(self.stations)
    self.current = self.stations[self.station_index]
    return self.current

def longPressPreset1through3(self):
    pass

def shortPressPreset1through3(self):
    pass

2 个答案:

答案 0 :(得分:0)

这是您定义和访问实例和calss属性的方法:

class YourClass:
    another_preset = 0 # the class attributes are defined here, and accessed the same way as instance attributes (plus can be accessed in the class itself like this: ‘YourClass.another_preset’),  but are shared among all instances
    def __init__(self):
        self.preset = 0  # instance variable - will be unique for every instance

    def set_preset_to(self, x):
        self.preset = x  # this is how you access the instance or class attributes inside a method

    def do_something_with_preset(self):
        self.preset += 2 # they can also be modified

答案 1 :(得分:0)

而不是在__init__上声明它们,您也可以在不__init__的情况下添加它们

class Radio:
    stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
    station_index = 0
    current = self.stations[0]
    presetStation1 = stations[0]
    presetStation2 = stations[0]
    presetStation3 = stations[0]

我不认为这是最优雅的解决方案,也不是很好的做法,因为预设站可能会在程序中发生变化,但它符合您的要求。