如何在python中扩展一个类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15526858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:19:33  来源:igfitidea点击:

How to extend a class in python?

pythonclassinterface

提问by omega

In python how can you extend a class? For example if I have

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

color.py

颜色.py

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

color_extended.py

color_extended.py

import Color

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

But this doesn't work... I expect that if I work in color_extended.py, then when I make a color object and use the getcolorfunction then it will return the object with the string " extended!" in the end. Also it should have gotton the init from the import.

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

Assume python 3.1

假设 python 3.1

Thanks

谢谢

采纳答案by NPE

Use:

用:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Colorfrom object, to make it a new-style class:

如果是这样的Python 2.x中,你也想得出color.Colorobject,使它成为一个新式类

class Color(object):
    ...

This is not necessary in Python 3.x.

这在 Python 3.x 中不是必需的。

回答by fyngyrz

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

另一种扩展(特别是添加新方法,而不是更改现有方法)类,甚至是内置类的方法是使用预处理器,它增加了扩展到 Python 本身范围之外/之上的能力,将扩展转换为在 Python 真正看到它之前的正常 Python 语法。

I've done this to extend Python 2's str()class, for instance. str()is a particularly interesting target because of the implicit linkage to quoted data such as 'this'and 'that'.

例如,我这样做是为了扩展 Python 2 的str()类。str()是一个特别有趣的目标,因为它隐式链接到引用的数据,例如'this''that'

Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuadbit:

这是一些扩展代码,其中唯一添加的非 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

After which I can write in the code fed to the preprocessor:

之后,我可以写入提供给预处理器的代码:

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'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

预处理器吃掉它,在没有猴子补丁的情况下吐出正常的 Python,Python 做我想要它做的事情。

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.

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

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is hereon GitHub.

我的预处理器的实施是一个堆栈溢出的答案太大,但对于那些谁可能会感兴趣,它是这里在GitHub上。