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

Can you initialize a variable inside the parameters of __init__()?

I was just wondering whether I’m able to initialize a variable inside the parameter of init()?

This is my code:

def __init__ (self, position = 0, memory = 0) :
        self.position = position
        self.memory = memory

So the question really is, is it possible to do position = 0 inside the init() function.

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

>Solution :

Yes, but then you’ll be overwriting any value of position passed as an argument. The default-value is only used if no argument is given.

You can check if the argument has a value that indicates some other value should be used instead (this is typically done with None, usually when you want the default to be a fresh instance of a mutable value).

def __init__(self, position=None, memory=0):
    if position is None:
        position = 0
    self.position = position
    self.memory = memory
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