Python 如何在类中接受用户输入并将其传递给条件
我目前正在尝试制作一个python脚本,在web浏览器中打开一个URL,现在我遇到了一个错误,Python 如何在类中接受用户输入并将其传递给条件,python,python-3.x,Python,Python 3.x,我目前正在尝试制作一个python脚本,在web浏览器中打开一个URL,现在我遇到了一个错误,NameError:name'song'未定义 import webbrowser class Halsey: def__init__(self): self.song = song def Badland(): print(" 1.Gasloine" "2.castle" "3.hold me down "
NameError:name'song'未定义
import webbrowser
class Halsey:
def__init__(self):
self.song = song
def Badland():
print(" 1.Gasloine"
"2.castle"
"3.hold me down "
"4.control")
song =int(input("Plase select a number from above list"))
if song == 1 :
url="https://www.youtube.com/watch?v=jU3P7qz3ZrM";
webbrowser.open(url,new=0)
嗯,您的
歌曲
变量仅在类的方法Badland
中可见。因此,您可以在定义该变量的相同方法中使用该变量,如下所示:
import webbrowser
class Halsey:
SONGS = (
("Gasloine", "https://www.youtube.com/watch?v=jU3P7qz3ZrM"),
("Castle", "url2"),
("Hold me down ", "url3"),
("Control", "url4"),
)
def __init__(self):
for i, song_name in enumerate(self.SONGS, 1):
print("{}. {}".format(i, song_name[0]))
song = int(input("Plase select a number from above list: "))
url = self.SONGS[song - 1][1]
webbrowser.open(url, new=0)
class Halsey:
SONGS = (
("Gasloine", "https://www.youtube.com/watch?v=jU3P7qz3ZrM"),
("Castle", "url2"),
("Hold me down ", "url3"),
("Control", "url4"),
)
def get_user_input():
for i, song_name in enumerate(self.SONGS, 1):
print("{}. {}".format(i, song_name[0]))
return int(input("Please select a number from above list: "))
instance = Halsey()
users_choice_int = instance.get_user_input()
url = self.SONGS[song - 1][1]
webbrowser.open(url, new=0)
。。。或者,您可以从类方法返回用户的输入,然后使用它,如下所示:
import webbrowser
class Halsey:
SONGS = (
("Gasloine", "https://www.youtube.com/watch?v=jU3P7qz3ZrM"),
("Castle", "url2"),
("Hold me down ", "url3"),
("Control", "url4"),
)
def __init__(self):
for i, song_name in enumerate(self.SONGS, 1):
print("{}. {}".format(i, song_name[0]))
song = int(input("Plase select a number from above list: "))
url = self.SONGS[song - 1][1]
webbrowser.open(url, new=0)
class Halsey:
SONGS = (
("Gasloine", "https://www.youtube.com/watch?v=jU3P7qz3ZrM"),
("Castle", "url2"),
("Hold me down ", "url3"),
("Control", "url4"),
)
def get_user_input():
for i, song_name in enumerate(self.SONGS, 1):
print("{}. {}".format(i, song_name[0]))
return int(input("Please select a number from above list: "))
instance = Halsey()
users_choice_int = instance.get_user_input()
url = self.SONGS[song - 1][1]
webbrowser.open(url, new=0)
此外,您还可以将变量保存在class属性中:self.song=int(输入(…)
,然后您可以通过self.song
在类方法内部访问它,或者通过instance.song
在类外部访问它
注意:不要忘记潜在的无效用户输入,您可以将您的song=int(输入…
包装在try/except
中
祝你好运!你认为
song
会从哪里来?它在类之外,也在你接受输入的Badland
方法之外。因此,你认为song
会从\u init\u
方法内部来,因为它实际上不是一个参数?你可能应该这样做回顾;这是一个经典的非一流课程。我是编程新手,所以我对编程了解不多,我正在尝试学习编程。然后我推荐一个结构化的教程,例如,如果你在OP的代码中解释了错误的东西,那就好了。