mandiatodos
mandiatodos

Reputation: 15

Call attribute of a class into another one

I have two classes: one with parameters of a configuration and another that represents a user.

class Configuration():
    def__init__(self, Attribute1):
       self.Attribute1 = Attribute1
    
    @property
    def Attribute1(self): 
       return self_Attribute1
    @Attribute1.setter
    def Attribute1(self, value): 
       self._Attribute1 = value

###############################

class User(): 
    def __init__(self, UserAttribute):
        self.UserAttribute = UserAttribute
    
    @property
    def Calculation(self): 
        return self.UserAttribute * Configuration.Attribute1

Obviously the code above doesn't work because ok this error:

TypeError: unsupported operand type(s) for -: 'int' and 'property'

That is cause because I'm trying to access to the attribute of Configuration class. So, how can I access to that attribute in the User class? Yes, I thought of inheritance, but that would mean I'd have to initialize every time the same attributes all over for every "user" class. That's not so handy... Thanks in advance!

Upvotes: 0

Views: 1195

Answers (2)

Dashfast
Dashfast

Reputation: 41

add this line of code after configuration class

config = Configuration()

then in user class instead of return self.UserAttribute * Configuration.Attribute1 do return self.UserAttribute * config.Attribute1

Upvotes: 1

quamrana
quamrana

Reputation: 39354

You should pass an instance of the Configuration class to your User:

class User(): 
    def __init__(self, UserAttribute, configuration):
        self.UserAttribute = UserAttribute
        self.configuration = configuration
    
    @property
    def Calculation(self): 
        return self.UserAttribute * self.configuration.Attribute1

configuration = Configuration(1)
user = User(attribute, configuration)

Upvotes: 1

Related Questions