问题描述
我需要扩展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中的cast接近,就像在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方法的扩展类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!