在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方式來完成您需要做的事情。
添加回答
舉報
0/150
提交
取消