我正在学习 Python 并试图进入类。我正在尝试抓取一些经常使用不同字符串来识别我需要的信息的网站。挑战在于我遇到了可能需要寻找数十个可能的字符串之一的情况。那时我是否继续嵌套 if 语句或创建新类等。
例如:在下面的类中,我正在返回的 html 中查找字符串 x、y 或 z。如果我找到 X 我需要执行一个函数。在 if 语句下面构建该函数是否最有效,或者我可以创建一个新函数并在此类中调用它(即,我创建一个名为 x_Found()
的新函数)来解析我需要的数据。
class Link:
def __init__(self, url):
self.url = url
x = 'abc'
y = 'zyx'
z = '123'
def get_html(self):
import urllib2
html = urllib2.urlopen(self.url()).read()
return html
def find_text(self):
html = self.get_html()
if x in html:
run a function called x_found()
elif y in html:
run a different function called y_found()
elif z in html:
run an even different function called z_found()
最佳答案
Lambda 和/或方法指针的字典。
method_map = {'x' : self.x_found, 'y': self.y_found, 'z':self.z_found}
strings_to_search = ['x', 'y', 'z']
for string in strings_to_search:
if string in html:
method_map[string]()
关于python - 面向对象编程初学者;更多方法与类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25538319/