0

How do I create an instance variable automatically when the class is initialized?

For example,

class AmortizationSchedule:
    __init__(self, principal, interest, num_periods):
        self.principal = principal
        self.interest = interest
        self.num_periods = num_periods

Now how do I create another attribute named schedule that is created automatically when I initialize the class?

3
  • 2
    self.schedule = some_value ? Commented Jun 28, 2018 at 21:03
  • self.schedule depends on self.interest, self.principal ect... Commented Jun 28, 2018 at 21:04
  • @RafaelC, that is possible, but it is better to have one "master" source data, and then use properties to calculate the values that are derived from those values. That way, any changes to the original data is automatically reflected. Commented Jun 28, 2018 at 21:09

1 Answer 1

3

This is a prefect use for @property.

You need a read-only property which does the calculation based on the other values. Properties are great because they look, feel, and behave just like attributes but their return value is calculated at the time they are accessed.

class AmortizationSchedule:
    def __init__(self, principal, interest, num_periods):
        self.principal = principal
        self.interest = interest
        self.num_periods = num_periods

    @property
    def schedule(self):
        return self.principal / self.num_periods # put the calculation here

To access it, you just treat it like another attribute:

foo = AmortizationSchedule(10000, 10, 50)
print(foo.schedule)
Sign up to request clarification or add additional context in comments.

4 Comments

Haha, I typed it a couple times before I understood it. :)
@RafaelC Sorry about that, sometimes it's hard to describe what you want.
By using @property when is schedule attribute created? Is it created when an instance of a class in created or when you call it? (e.g if amort is an instance is schedule created on the fly when you call amort.schedule?
@spitfiredd, the @property decorator modifies the method that follows it into a data descriptor at the time of class creation. The main point is that this data descriptor "property" runs the code in it's function every time you access it. Nothing is pre-calculated.

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.