Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

setting attribute in __init__ with method in python?

I’m learning python. I’d like for self.characteristic to be set to 5 when an object of the class is created. I’m using the set.characteristic method, because in reality there would be a bunch of calculations to reach the value 5. I’d expect the output of my code below to be 5, but I get None. Why? Thanks!

class AnyClass:

    def __init__(self):
        self.characteristic = self.set_characteristic()


    def set_characteristic(self):
        # in reality would do a bunch of calculations 
        self.characteristic = 5


obj = AnyClass()
print(obj.characteristic)

# Output: None 
# Expected output: 5

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You forgot to return the desired value in your function.

def set_characteristic(self):
    # in reality would do a bunch of calculations 
    return 5

When you do not return a value, function returns None.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading