将基类转换为派生类 python(或更多 pythonic 扩展类的方式) [英] Cast base class to derived class python (or more pythonic way of extending classes)
问题描述
我需要扩展 Networkx python 包并向 Graph
类添加一些方法以满足我的特殊需要
I need to extend the Networkx python package and add a few methods to the Graph
class for my particular need
我想这样做的方法是简单地派生一个新类,比如 NewGraph
,然后添加所需的方法.
The way I thought about doing this is simplying deriving a new class say NewGraph
, and adding the required methods.
然而,networkx 中有几个其他函数可以创建和返回 Graph
对象(例如生成随机图).我现在需要将这些 Graph
对象转换为 NewGraph
对象,以便我可以使用我的新方法.
However there are several other functions in networkx which create and return Graph
objects (e.g. generate a random graph). I now need to turn these Graph
objects into NewGraph
objects so that I can use my new methods.
这样做的最佳方法是什么?或者我应该以完全不同的方式解决问题?
What is the best way of doing this? Or should I be tackling the problem in a completely different manner?
推荐答案
如果你只是添加行为,而不是依赖额外的实例值,你可以分配给对象的__class__
:
If you are just adding behavior, and not depending on additional instance values, you can assign to the object's __class__
:
from math import pi
class Circle(object):
def __init__(self, radius):
self.radius = radius
def area(self):
return pi * self.radius**2
class CirclePlus(Circle):
def diameter(self):
return self.radius*2
def circumference(self):
return self.radius*2*pi
c = Circle(10)
print c.radius
print c.area()
print repr(c)
c.__class__ = CirclePlus
print c.diameter()
print c.circumference()
print repr(c)
打印:
10
314.159265359
<__main__.Circle object at 0x00A0E270>
20
62.8318530718
<__main__.CirclePlus object at 0x00A0E270>
这与 Python 中的强制转换"非常接近,就像在 C 中进行强制转换一样,如果不考虑这个问题,就不能这样做.我发布了一个相当有限的示例,但如果您可以保持在约束范围内(只需添加行为,没有新的实例变量),那么这可能有助于解决您的问题.
This is as close to a "cast" as you can get in Python, and like casting in C, it is not to be done without giving the matter some thought. I've posted a fairly limited example, but if you can stay within the constraints (just add behavior, no new instance vars), then this might help address your problem.
这篇关于将基类转换为派生类 python(或更多 pythonic 扩展类的方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!