如何在python中扩展类?

2024-05-17 14:01:47 发布

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

在python中,如何扩展类?例如,如果我有

颜色.py

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

颜色扩展.py

import Color

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

但这不管用。。。 我希望如果我在color_extended.py中工作,那么当我创建一个颜色对象并使用getcolor函数时,它将返回带有字符串“extended!”最后。它还应该从导入中获取init。

假设python 3.1

谢谢


Tags: 对象函数字符串pyimportselfextendedreturn
2条回答

扩展类(特别是添加新方法,而不是更改现有方法)的另一种方法,甚至是内置类,是使用一个预处理器,该预处理器增加了扩展到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'

预处理器会吃掉它,在不使用monkeypatching的情况下吐出普通的Python,Python会按照我希望的那样做。

正如c预处理器向c添加功能一样,Python预处理器也可以向Python添加功能。

我的预处理器实现对于堆栈溢出答案来说太大了,但是对于那些可能感兴趣的人来说,它是GitHub上的here

使用:

import color

class Color(color.Color):
    ...

如果这是Python 2.x,那么您还需要从object派生color.Color,使其成为new-style class

class Color(object):
    ...

这在Python3.x中是不必要的

相关问题 更多 >