为了账号安全,请及时绑定邮箱和手机立即绑定

在python中从Base通用创建Derived类

在python中从Base通用创建Derived类

守候你守候我 2021-03-24 18:14:44
在SO上发现了一些问题,但仍然没有答案...有一个数据类class Proxy(object):    def __init__(self, ip, port):        self.ip = ip        self.port = port有一个getter类,应该从不同的来源读取这些数据class FileProxyGetter(ProxyGetter):    def __init__(self, fname = "d:\\proxies.txt"):        self.fileName = fname     def Get(self):        proxies = []        f = open(self.fileName)        for l in f.xreadlines():             proxies.append(Proxy.fromstring(l[:-1]))        f.close()        return proxies    def Update(self):        return []我需要一个具有更多选项的Proxy类,例如class SecureProxy(Proxy):    def __init__(self, ip, port):        super(SecureProxy, self).__init__(ip, port)        self.transparent = None现在,我要改进FileProxyGetter,如下所示:class FileSecureProxyGetter(FileProxyGetter):    def Get(self):        proxies = super(FileProxyGetter, self).Get()        secureProxies = []        for proxy in proxies:            # Create or Cast Proxy to SecureProxy.            # The transparent should be initialized to None or any other value that I may need            secureProxies.append(SecureProxy(proxy))        return secureProxies因此,我该如何在Python中从基类强制转换或创建派生类的实例。如果不更改所需的类,那就更好了。还是可以建议一些开发这种关系和体系结构的更蟒蛇的方法?
查看完整描述

2 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

如果需要,您可以自己调用init。或者,您可以在内部进行dict交换,SecureProxy.__new__(proxy)以模仿其他语言的“不安全的向上转换”行为。尽管Python确实做到了这一点,但这并不是一个好的OO设计(在C / C ++中做同样的事情很可能会使您无声的内存损坏;或者在Java中是ClassCastException)。不过,更重要的是,您真正想做什么?也许有更好,更多的面向对象和更多的pythonic方式来完成您需要做的事情。

查看完整回答
反对 回复 2021-03-26
  • 2 回答
  • 0 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号