初学者OOP;更多方法vs类

2024-04-26 00:21:28 发布

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

我在学习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()

Tags: 函数run字符串inselfurlgetif
2条回答

在这种情况下,您不应该使用if语句。最好创建一个字典,将字符串映射到函数,然后在其中调用适当的函数。你知道吗

尝试以下操作:

def string1_found():
    print "Found a string 1"

foo = {}
foo['string1'] = string1_found

那你可以一个接一个地打电话

myfunc = foo['string1']
myfunc()

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]()

相关问题 更多 >