【发布时间】:2016-01-19 10:29:34
【问题描述】:
如果我有 2 个这样定义的类:
class A(object):
a = 10
class B(A):
b = 20
如果我创建一个对象:
c = A()
然后做:
c.__class__ = B
改变(“升级”)对象的类,保持主要的类属性和方法,获得次要的类属性和方法,是一种有效的方式吗?
如果为真,这仅在我们将对象更改为的类继承自前一个类的情况下才有意义?最好的问候。
更新:
提供更多上下文。 我有以下类 EmbrionDevice。
class EmbrionDevice(object):
def __init__(self, device_info, *args, **kwargs):
super(EmbrionDevice, self).__init__(*args, **kwargs)
# Serial number unique 64-bit address factory-set
self.shl = device_info['source_addr_long']
# 16-bit network address
self.my = device_info['source_addr']
# Node identifier
self.ni = device_info['node_identifier']
# Parent Address
self.pa = device_info['parent_address']
# Device type, 0-coordinator, 1-router, 2-End Device
self.dt = device_info['device_type']
# Device type identifier xbee or Digi device
self.dd = device_info['device_type_identifier']
# Device attributes summary in a dictionary
self.info = device_info
# Embrion future function
self.function_identifier = None
# Device state definition
self.state = DEV_STATE_CODES['embrion']
self.status = DEV_STATUS_CODES['no status']
我稍后想更改/升级到以下特定设备类之一:
class PassiveDevice(EmbrionDevice):
pass
class ActiveDevice(EmbrionDevice):
pass
基本上我想简化我的副本,避免复制所有属性。
【问题讨论】:
-
我不会打电话是一种“有效的方式”;这是一个黑客。这种黑客攻击可能有用例,但您通常希望避免黑客攻击。
-
你没有“升级”一个类;它不是语言功能。您可以根据来自另一个类实例的状态实例化一个类,但这相当于只实例化一个类。
-
什么是获得相同结果的有效方法,而不必将旧类的所有对象属性复制到新类?
-
您应该添加更多关于您的用例的上下文。因为,无论这在技术上是否可行,它都是非常丑陋和骇人听闻的,而且是一种非常糟糕的设计方法。
-
由于您正在编写真正的代码,而不是玩弄变形对象,请检查 zope.interface 包和适配器 - 它们可能更适合您。 docs.zope.org/zope.interface(不要害怕名称中的“zope”:zope.interface 是一个独立的包)
标签: python python-2.7 python-internals