如何扩展python模块?向`python-twitter` 包添加新功能 [英] How do I extend a python module? Adding new functionality to the `python-twitter` package
问题描述
扩展现有 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 化和破坏性最小的方法,将它们添加到 python-twitter
包模块中,而无需更改该模块的核心.
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)
更难(可能不是 Pythonic)的方法:
将 * 从 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
THIS WAS PRESERVED
我不确定 extmodule.py 中的双重导入是否是 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` 包添加新功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!