python类的派生_将基类转换为派生类python(或更多pythonic方法的扩展类)

I need to extend the Networkx python package and add a few methods to the Graph class for my particular need

The way I thought about doing this is simplying deriving a new class say NewGraph, and adding the required methods.

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?

解决方案

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)

Prints:

10

314.159265359

20

62.8318530718

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值