亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在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?;蛘撸梢栽趦炔窟M行dict交換,SecureProxy.__new__(proxy)以模仿其他語言的“不安全的向上轉換”行為。盡管Python確實做到了這一點,但這并不是一個好的OO設計(在C / C ++中做同樣的事情很可能會使您無聲的內存損壞;或者在Java中是ClassCastException)。不過,更重要的是,您真正想做什么?也許有更好,更多的面向對象和更多的pythonic方式來完成您需要做的事情。

查看完整回答
反對 回復 2021-03-26
  • 2 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號