English 中文(简体)
灭 object
原标题:Python object conversion
  • 时间:2010-01-28 08:59:13
  •  标签:
  • python

假设我们有一个标的<代码>k> 类型<代码>>, 类别A。 我们界定了第二个<代码>类别B(A)。 有哪些最佳做法用于“星号”物体k->,并保存<代码>k中的所有数据?

最佳回答

这确实是“等级转换”,但受到附带损害。 创建另一个物体并替换其第__dict_,作为脑能的载体,将是更安全的,但这一守则确实是你要求的,没有制造新的物体。

class A(object):
    pass

class B(A):
    def __add__(self, other):
        return self.value + other


a = A()
a.value = 5

a.__class__ = B

print a + 10
问题回答
a = A() # parent class
b = B() # subclass
b.value = 3 # random setting of values

a.__dict__ = b.__dict__ # give object a b s values

# now proceed to use object a

这是否满足了你的使用情况? 注: 只有在物体a而不是B类变量的情况下才能获得b的典型变量。 此外,对a项变量的修改将修改b项中的变量,除非你做了深度的改动:

import copy
a.__dict__ = copy.deepcopy(b.__dict__)
class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b

class B(A):
    def __init__(self, parent_instance, c):
        # initiate the parent class with all the arguments coming from
        # parent class __dict__
        super().__init__(*tuple(parent_instance.__dict__.values()))
        self.c = c

a_instance = A(1, 2)
b_instance = B(a_instance, 7)
print(b_instance.a + b_instance.b + b_instance.c)
>> 10

或者你可以在这方面发挥良好作用:

def class_converter(convert_to, parent_instance):
    return convert_to(*tuple(parent_instance.__dict__.values()))

class B(A):
    def __init__(self, *args):
        super().__init__(*args)
            self.c = 5

但是,使用第二手法,我无法说明如何通过额外价值。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签