1

I'd like to create a class that has 2 input attributes and 1 output attribute such that whenever one of the input attributes are modified the output attribute is modified automatically

I've tried defining the attributes as instance variables within and outside the constructor function but in either case, after instantiating the object, the output attribute remains fixed at the value set at the moment of instantiation

class Example():

    def __init__(self,n):
        self.name=n

    inA=1
    inB=1

    if inA==1 and inB==1:
        outA=1
    else:
        outA=0

when instantiated outA is set to 1 as expected but if I try to update: object.inA=0

object.outA remains 1 whereas I need it to be updated to 0

Trying to avoid the use of functions if possible. New to python and OOP so sorry if this question is nonsensical or has an obvious answer

1
  • 1
    Code defined at class level (outside of a method) is run only once at class initialization in the context of the class (not the instance). Commented May 14, 2019 at 3:17

3 Answers 3

5

If you want instance attributes that depend on other instance attributes, properties are the way to go.

class Example:
    def __init__(self, n):
        self.name = n
        self.inA = 1
        self.inB = 1

    @property
    def outA(self):
        return self.inA and self.inB

You access outA like a regular instance attribute, obj.outA.

>>> my_obj = Example("example")
>>> my_obj.outA
1

Changing the attributes inA and inB affect outA.

>>> my_obj.inA = 0
>>> my_obj.outA
0
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a function in the class and some other minor changes:

class Example():

    def __init__(self,n):
        self.name=n
        self.inA=1
        self.inB=1

    def f(self):
        if self.inA==1 and self.inB==1:
            self.outA=1
        else:
            self.outA=0

To call it:

a = Example('foo')
a.inA = 0
a.f()
print(a.outA)

Output:

0

As you can see, taking out:

a.f()

line would make it give an error:

AttributeError: 'Example' object has no attribute 'outA'

1 Comment

sorry new to stackexchange didn't see the comment/know about accepting until now
0

Do you want it to return your output?

Expanding on U9-Forward's answer:

class Example():

    def __init__(self,n):
        self.name = n
        self.inA = 1
        self.inB = 1

    def f(self):
        return self.inA and self.inB

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.