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

On the need for __init__() function in Python class

I have a very basic question about why I need __init__ in declaring a class in Python.

For example, in this link, an example was introduced

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age) 

But the above example requires a series of arguments as ("John", 36). When the number of arguments is large, they may be error-prone in the input. I can use *args, but it also requires the order of argument. If I just provide a default value of the name and age, and modify in need, will it simplify the practice? For example

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 Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
    
class Person2:
  name = "John"
  age = 36    
  
class Person3:
  def __init__(self, *args):
    self.name = args[0]
    self.age = args[1]
      

p1 = Person("John", 36)
print(p1.name)
print(p1.age)

p2 = Person2()
print(p2.name)
print(p2.age)


p2.name = "Mike"
p2.age = 35
print(p2.name)
print(p2.age)


p3 = Person3("John", 36)
print(p3.name)
print(p3.age)

Person2 is perhaps the simplest. But, will Person2 be a good practice?

>Solution :

You may want to read into the difference of class and an instance of a class: Person2 will not fly as every person would be the same. You use the class here basically as a namespace without further usage.

Person3 is basically a bad version of Person1.

Person1 will be ok and not error prone as you can also pass the arguments as keyword arguments (Person(name=..., age=...).

You may also have a look at dataclasses as they remove this kind of boilerplate: https://docs.python.org/3/library/dataclasses.html

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