Dio
Dio

Reputation: 241

A class instance initializing with previously initialized attributes

I have a slight complication with my code. I want the pirate attribute to take the value True if the other two attributes are higher than some number when summed up and multiplied by some factor.

For instance, maybe I want the pirate attribute to be True only if social*0.6 + fixed is greater than 5, and false otherwise.

import random

class consumer(object):
"""Initialize consumers"""
    def __init__(self, fixed, social,pirate):
        self.social = social
        self.fixed = fixed
        self.pirate = pirate

"""Create an array of people"""
for x in range(1,people):
    consumerlist.append(consumer(random.uniform(0,10),random.uniform(0,10),True))
    pass

Upvotes: 0

Views: 53

Answers (2)

Bouke
Bouke

Reputation: 1614

In response to Moses answer: Using a calculated property is safer than calculating the pirate value at initialization only. When decorating a method with the @property attribute, it acts as a property (you don't have to use brackets as is the case for methods), which is always up to date when the social member is changed afterwards.

class Consumer(object):

    def __init__(self, fixed, social):
        self.fixed = fixed
        self.social = social

    @property
    def pirate(self):
        return self.social * 0.6 + self.fixed > 5

consumer1 = Consumer(1, 12)
print("Value of pirate attribute: " + str(consumer1.pirate))

Upvotes: 2

Moses Koledoye
Moses Koledoye

Reputation: 78554

You need to store the random values for fixed and social and then use them for the comparison that generates pirate:

for x in range(1,people):
     fixed = random.uniform(0,10)
     social = random.uniform(0,10)
     pirate = (social * 0.6 + fixed) > 5 # boolean
     consumerlist.append(consumer(fixed, social, pirate))

That pass in your for is redundant

Upvotes: 0

Related Questions