猿问

在python中从Base通用创建Derived类

在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中从基类强制转换或创建派生类的实例。如果不更改所需的类,那就更好了。


还是可以建议一些开发这种关系和体系结构的更蟒蛇的方法?



守候你守候我
浏览 176回答 2
2回答

呼唤远方

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

相关分类

Python
我要回答