【发布时间】:2013-05-20 23:08:45
【问题描述】:
在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 []
我需要一个具有更多选项的代理类,例如
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 中普遍地从基类转换或创建派生类的实例。如果不需要更改类会更好。
或者你能建议更多的 Pythonic 方式来开发这种关系和架构?
【问题讨论】:
-
我不明白这一点 - 你有
Proxy和FileProxyGetter。然后你写SecureProxy并希望FileSecureProxyGetter自动出现 - 对吗? -
@GillBates 不,我是手动创建的。我想从只调用 SecureProxy 构造函数的代理中创建 SecureProxy
-
并不是说它解决了你的问题,而是你读取文件行的方式有两个问题。首先,使用
with open(..) as f:打开和自动关闭文件,即使在出现异常或提前返回的情况下也能正常工作。然后,for line in f:是遍历文件行的惯用方式。也就是说,为了解决您手头的问题,您是否考虑过使用在工厂中注册所有派生类的元类?或者,您可以将正确的类型传递给ProxyGetter.Get()。
标签: python class architecture derived-class base-class