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
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?
CodePudding user response:
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