问题描述
扩展现有Python模块的最佳实践是什么?在这种情况下,我想通过向基础API类添加新方法来扩展python-twitter
包.
What are the best practices for extending an existing Python module – in this case, I want to extend the python-twitter
package by adding new methods to the base API class.
我看过tweepy
,我也很喜欢.我只是发现python-twitter
更容易理解并扩展了我想要的功能.
I've looked at tweepy
, and I like that as well; I just find python-twitter
easier to understand and extend with the functionality I want.
我已经编写了方法-我试图找出在不更改此模块核心的情况下将其添加到python-twitter
软件包模块中的最Pythonic且破坏性最小的方法.
I have the methods written already – I'm trying to figure out the most Pythonic and least disruptive way to add them into the python-twitter
package module, without changing this modules’ core.
推荐答案
几种方法.
简单方法:
不扩展模块,扩展类.
Don't extend the module, extend the classes.
exttwitter.py
exttwitter.py
import twitter
class Api(twitter.Api):
pass
# override/add any functions here.
缺点:twitter中的每个类都必须位于exttwitter.py中,即使它只是一个存根(如上)
Downside : Every class in twitter must be in exttwitter.py, even if it's just a stub (as above)
一种更困难的(可能是非Python的)方式:
将*从python-twitter导入一个模块,然后进行扩展.
Import * from python-twitter into a module that you then extend.
例如:
basemodule.py
basemodule.py
class Ball():
def __init__(self,a):
self.a=a
def __repr__(self):
return "Ball(%s)" % self.a
def makeBall(a):
return Ball(a)
def override():
print "OVERRIDE ONE"
def dontoverride():
print "THIS WILL BE PRESERVED"
extmodule.py
extmodule.py
from basemodule import *
import basemodule
def makeBalls(a,b):
foo = makeBall(a)
bar = makeBall(b)
print foo,bar
def override():
print "OVERRIDE TWO"
def dontoverride():
basemodule.dontoverride()
print "THIS WAS PRESERVED"
runscript.py
runscript.py
import extmodule
#code is in extended module
print extmodule.makeBalls(1,2)
#returns Ball(1) Ball(2)
#code is in base module
print extmodule.makeBall(1)
#returns Ball(1)
#function from extended module overwrites base module
extmodule.override()
#returns OVERRIDE TWO
#function from extended module calls base module first
extmodule.dontoverride()
#returns THIS WILL BE PRESERVED\nTHIS WAS PRESERVED
我不确定extmodule.py中的double import是否为pythonic-您可以将其删除,但是这样您就无法处理想要扩展basemodule命名空间中的函数的用例.
I'm not sure if the double import in extmodule.py is pythonic - you could remove it, but then you don't handle the usecase of wanting to extend a function that was in the namespace of basemodule.
对于扩展类,只需创建一个新的API(basemodule.API)类即可扩展Twitter API模块.
As far as extended classes, just create a new API(basemodule.API) class to extend the Twitter API module.
这篇关于如何扩展python模块?在python-twitter包中添加新功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!