如何在python中扩展一个类? [英] How to extend a class in python?
问题描述
在python中你如何扩展一个类?例如,如果我有
In python how can you extend a class? For example if I have
颜色.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
函数时,它将返回带有字符串extended!"的对象.到底.它也应该从导入中获得 init.
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,您还需要从 object
派生 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屋!