Addicted2Cookies
Addicted2Cookies

Reputation: 84

Why should I use a method instead of using __init__()?

In a tutorial that I was watching for Python OOP, they used a method instead of putting it under __init__, I want to know what's the difference in creating a method when I can just put it under __init__.

class Employee:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
        
    def fullname(self):
        return f'{self.firstname} {self.lastname}'

That is the code that they used, and I use the code below which works completely fine.

class Employee:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
        self.fullname = f'{firstname} {lastname}'

Upvotes: 0

Views: 96

Answers (1)

Amit Singh
Amit Singh

Reputation: 3063

It's a design decision. Keeping something as a variable will mean retaining it as long as the object exists. Defining it as a function will calculate it's value at runtime.

Since fullname is something that can be easily computed at runtime and is derived from already existing variables firstname and lastname making it somewhat redundant that's why they recommended it to be designed to be a function rather than a variable.

A scenario where you would likely want to store it as a variable is if that value is used very frequently or is computationally expensive to calculate at runtime, you would then have stored it once and re-used it.

But since this is a design decision, it varies case-to-case.

Upvotes: 3

Related Questions