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

2024-09-28 21:43:18 发布

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

我做了这个简单的程序来模拟一个电台。我需要弄清楚如何根据当前电台设置预设。你知道吗

以下是菜单选项:

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”时,收音机将寻找下一个电台。这是通过类方法[def seekNext(self):]

所以我需要帮助的是,在使用CLASS方法[def longPressPreset1through3(self):]选择选项“2、3和4”时,如何将当前电台设置为预设?你知道吗

另外,设置预设后,如何使用CLASS方法[def shortpresspet1through3(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

Tags: 方法selfindexdef选项currentprogramclass
2条回答

以下是定义和访问实例和计算属性的方式:

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

相反,在__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]

我不认为这是最优雅的解决方案或良好的做法,虽然,因为预设电台可能会改变在程序中,但它符合您的要求。你知道吗

相关问题 更多 >