如何扩展一个类在python? [英] How to extend a class in python?

查看:65
本文介绍了如何扩展一个类在python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

color.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!"

但这不工作...
我希望如果我在 color_extended.py ,那么当我创建一个颜色对象并使用 getcolor 函数时,它将返回带有字符串的对象扩展!到底。

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 getcolor function then it will return the object with the string " extended!" in the end. Also it should have gotton the init from the import.

假设python 3.1

Assume python 3.1

感谢

推荐答案

使用:

import color

class Color(color.Color):
    ...

如果这是Python 2.x,你还需要从对象中派生 color.Color 新式类

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

class Color(object):
    ...

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

This is not necessary in Python 3.x.

这篇关于如何扩展一个类在python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆