栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何扩展python模块?在python-twitter包中添加新功能

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何扩展python模块?在python-twitter包中添加新功能

几种方法。

简单的方法:

不要扩展模块,扩展类。

exttwitter.py

import twitterclass Api(twitter.Api):    pass     # override/add any functions here.

缺点:twitter中的每个类都必须位于exttwitter.py中,即使它只是一个存根(如上所述)

一种更困难的(可能是非Python的)方式:

将*从python-twitter导入一个模块,然后进行扩展。

例如 :

basemodule.py

 class Ball():    def __init__(self,a):        self.a=a    def __repr__(self):        return "Ball(%s)" % self.adef makeBall(a):    return Ball(a)def override():    print "OVERRIDE ONE"def dontoverride():    print "THIS WILL BE PRESERVED"

extmodule.py

from basemodule import *import basemoduledef makeBalls(a,b):    foo = makeBall(a)    bar = makeBall(b)    print foo,bardef override():    print "OVERRIDE TWO"def dontoverride():    basemodule.dontoverride()    print "THIS WAS PRESERVED"

runscript.py

import extmodule#pre is in extended moduleprint extmodule.makeBalls(1,2)#returns Ball(1) Ball(2)#pre is in base moduleprint extmodule.makeBall(1)#returns Ball(1)#function from extended module overwrites base moduleextmodule.override()#returns OVERRIDE TWO#function from extended module calls base module firstextmodule.dontoverride()#returns THIS WILL BE PRESERVEDnTHIS WAS PRESERVED

我不确定extmodule.py中的double import是否是pythonic
-您可以将其删除,但是这样您就无法处理想要扩展basemodule命名空间中的函数的用例。

至于扩展类,只需创建一个新的API(basemodule.API)类即可扩展Twitter API模块。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650539.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号