python - 面向对象编程初学者;更多方法与类

标签 python class oop python-2.7

我正在学习 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/

相关文章:

php - 使用 PDO 返回上次插入 ID

c++ - Boost.Python - 公开一个类

仅适用于开发环境的 Python 应用程序多线程

python - 从类中的静态方法 Python 填充一次静态变量

java - Android:Java 是否对许多类效率较低

c# - 抽象子类共有的方法,但它使用子类特定类型

python - 在 python 中关闭 Firefox Web 驱动程序时出现意外警报

python - 使用 Python lxml 模块保留文本节点中的特殊字符

class - UML 类图 - 来自其他类的方法 - 哪个连接器?

oop - 领域模型和对象模型