Found some questions on SO but still have no answer... There is a data class
class Proxy(object):
def __init__(self, ip, port):
self.ip = ip
self.port = port
There is a getter class which is supposed to read these data from different sources
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 []
I need to have a Proxy class with more options like
class SecureProxy(Proxy):
def __init__(self, ip, port):
super(SecureProxy, self).__init__(ip, port)
self.transparent = None
Now I want to improve FileProxyGetter as follows:
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
So how do I cast or create an instance of derived class from base class in Python universally. It would be better if no changes to the classes needed.
Or can you suggest more pythonic way of developing such relationships and architecture?
ProxyandFileProxyGetter. Then you writeSecureProxyand you want thatFileSecureProxyGetterappear automatically - thats right?with open(..) as f:to open and automatically close the file, which works even in the presence of exceptions or an early return. Then,for line in f:is the idiomatic way to iterate over the lines of a file. That said, to address your problem at hand, have you considered using a metaclass that registers all derived classes in a factory? Alternatively, you could pass the correct type toProxyGetter.Get().