1

Hi I want to define an object value as a sum of values of two objects of the same class before I know what the value of those 2 objects is. I need to do something like:

`A=: B+C
 B=10
 C=20 
 print A`

I have a class Set and I'm trying something like:

class Set(object):
    def __init__(self, w):
        self.value=w
a=Set
c=a
a(10)
print c

But c is still class instead of object instance. Can somebody help me?

2 Answers 2

1

a is a class Set and so is c. a(10) generates an instance but discards it right away. You need to create instances and assign values later. Something like that:

class Sum(object):
    def __init__(self, *values):
        self.values = values

    @property
    def value(self):
        return sum(v.value for v in self.values)

class Value(object):
    def __init__(self, value=0):
        self.value=value

b = Value()
c = Value()
a = Sum(b,c)
b.value = 10
c.value = 20
print a.value
Sign up to request clarification or add additional context in comments.

2 Comments

it doesn't work, gives me TypeError: unsupported operand type(s) for +: 'Value' and 'Value' error
and then if I do b = Value() c = Value() a = Sum(b.value,c.value) b.value = 10 c.value = 20 print a.value I get a.value=0, which should be 30.
0

One way is to leverage dict of object. You can use __dict__ function of class.

class First:
    a = "A"
    b = "B"
    c = "C"

class Second:
    a = None
    b = None
    c = None
    d = "D"
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

Now you can initialize Second class, using First class instance as follows:

first = First()
second = Second(**(first.__dict__))
print(second.a)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.