标签:python module python-module tweepy python-twitter
扩展现有Python模块的最佳实践是什么 – 在这种情况下,我想通过向基本API类添加新方法来扩展python-twitter包.
我看过tweepy,我也喜欢它;我发现python-twitter更容易理解并扩展我想要的功能.
我已经编写了方法 – 我试图弄清楚将Pythonic和最不具破坏性的方法添加到python-twitter包模块中,而不改变这个模块的核心.
解决方法:
几种方式.
简单的方法:
不要扩展模块,扩展类.
exttwitter.py
import twitter
class Api(twitter.Api):
pass
# override/add any functions here.
缺点:twitter中的每个类都必须在exttwitter.py中,即使它只是一个存根(如上所述)
一种更难(可能是非pythonic)的方式:
将*从python-twitter导入到您随后扩展的模块中.
例如 :
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
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
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中的双重导入是否是pythonic – 你可以删除它,但是你不会处理想要扩展basemodule命名空间中的函数的用例.
就扩展类而言,只需创建一个新的API(basemodule.API)类来扩展Twitter API模块.
标签:python,module,python-module,tweepy,python-twitter 来源: https://codeday.me/bug/20190923/1813416.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。