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

Why can I set properties during instantiation through __init__, but not through another method?

This is working

class a:
    def __init__(self,ka,sif):
        self.ka = ka
        self.sif = sif
    def b(self):
        pass

c = a("d","e")
c
print(c.ka,c.sif)

but

This is not working

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

class a:
    def __init__(self):
        pass
    def b(self,ka,sif):
        self.ka = ka
        self.sif = sif

c = a().b("d","e")
c
print(c.ka,c.sif)

Why?

I expected the get same result. Why these are not have same results.

>Solution :

a("d","e") will call __init__ and return the new instance of the class a. Regular methods do not have this behavior.

The b method does not return anything (so it implicitly returns None); if you want to be able to chain that method, add return self at the end.

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