如何在Python中扩展类?

134 投票
4 回答
225164 浏览
提问于 2025-04-17 19:45

在Python中,如何扩展一个类呢?比如我有一个文件叫做

color.py

class Color:
    def __init__(self, color):
        self.color = color
    def getcolor(self):
        return self.color

还有一个文件叫做

color_extended.py

import Color

class Color:
    def getcolor(self):
        return self.color + " extended!"

但是这样做不行……我希望如果我在 color_extended.py 中工作,当我创建一个颜色对象并使用 getcolor 函数时,它能返回一个字符串,最后加上 " extended!"。而且它应该能从导入的部分获取初始化内容。

假设使用的是Python 3.1

4 个回答

3

还有一种方法可以扩展类(这里指的是添加新方法,而不是修改已有的方法),即使是内置的类,也可以使用一个预处理器。这个预处理器的作用是让你在Python的范围之外添加扩展,然后在Python真正看到这些内容之前,把扩展转换成正常的Python语法。

举个例子,我曾经用这个方法扩展过Python 2的 str() 类。str() 类特别有趣,因为它和用引号括起来的数据(比如 'this''that')有隐含的联系。

下面是一些扩展的代码,唯一添加的非Python语法是 extend:testDottedQuad 这一部分:

extend:testDottedQuad
def testDottedQuad(strObject):
    if not isinstance(strObject, basestring): return False
    listStrings = strObject.split('.')
    if len(listStrings) != 4: return False
    for strNum in listStrings:
        try:    val = int(strNum)
        except: return False
        if val < 0: return False
        if val > 255: return False
    return True

之后,我可以在传给预处理器的代码中写:

if '192.168.1.100'.testDottedQuad():
    doSomething()

dq = '216.126.621.5'
if not dq.testDottedQuad():
    throwWarning();

dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
    print 'well, that was fun'

预处理器会处理这些内容,输出正常的Python代码,而不需要进行猴子补丁(即不修改已有的代码),然后Python就会按照我想要的方式运行。

就像C语言的预处理器为C语言添加功能一样,Python的预处理器也可以为Python添加功能。

我的预处理器实现比较复杂,不适合在Stack Overflow上回答,但如果你感兴趣,可以在这里找到它,放在GitHub上。

20
class MyParent:

    def sayHi():
        print('Mamma says hi')
from path.to.MyParent import MyParent

class ChildClass(MyParent):
    pass

这样一来,ChildClass的一个实例就会继承sayHi()这个方法。

134

使用:

import color

class Color(color.Color):
    ...

如果这是Python 2.x版本,你还需要让color.Color继承自object,这样它就变成了一个新式类

class Color(object):
    ...

在Python 3.x版本中,这个步骤就不需要了。

撰写回答