在python中从Base通用创建派生类

2024-10-03 23:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在某某身上发现了一些问题,但仍然没有答案。。。有一个数据类

class Proxy(object):
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

有一个getter类应该从不同的源读取这些数据

^{pr2}$

我需要一个有更多选项的代理类

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中从基类转换或创建派生类的实例呢。如果不改变所需的类会更好。在

或者你能给我一个更像Python的方式来发展这种关系和架构吗?在


Tags: 数据selfipnonegetinitportdef
1条回答
网友
1楼 · 发布于 2024-10-03 23:24:26

您可以使用继承:

class FileProxyGetter(ProxyGetter):
    ...
    def MakeProxy(self, *args, **kwargs):
        return Proxy.fromstring(*args, **kwargs)
    def Get(self):
        ...
           proxies.append(self.MakeProxy(l[:-1]))
        ...
    ...
class FileSecureProxyGetter(FileProxyGetter):
    def MakeProxy(self, *args, **kwargs):
        return SecureProxy.fromstring(*args, **kwargs)

但在这种情况下,使用组合可能更有用。在

^{pr2}$

编辑:python中切换对象类型的一个肮脏的技巧:

>>> class A(object):
...     def foo(self):
...         print 'hello A'
... 
>>> class B(object):
...     def foo(self):
...         print 'hello B'
... 
>>> a = A()
>>> a.foo()
hello A
>>> a.__class__
<class '__main__.A'>
>>> a.__class__ = B
>>> a.foo()
hello B

两个不同类型的对象共享同一状态的另一个肮脏伎俩:

>>> class B(object):
...     def rename(self, name):
...         self.name = name
... 
>>> class A(object):
...     def say(self):
...         print 'Hello', self.name
... 
>>> a, b = A(), B()
>>> a.__dict__ = b.__dict__
>>> b.rename('john')
>>> a.say()
Hello john
>>> a.rename('mary')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'rename'
>>> b.say()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'B' object has no attribute 'say'

然而,这些技巧虽然在Python中是可能的,但我不认为它们是pythonic,也不是一个好的OO设计。在

Python 3.x及更高版本中的另一种可能,它删除了“unbound method”而不是使用常规函数:

>>> class A(object):
...     def say(self):
...         print('Hello', self.name)
... 
>>> class B(object):
...     def rename(self, name):
...         self.name = name + name
... 
>>> a = A()
>>> B.rename(a, 'josh')
>>> a.say()
Hello joshjosh

相关问题 更多 >