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?
1 Answer 1
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
dataclassfrom thedataclassespackage from the standard library. If you plan for more complex functionality you should stick with a conventional implementation that includes named arguments and an__init__(in other words, don't ever doPerson3).Foo(Bar(a, b), Baz(c, d)instead ofFoo(a, b, c, d), for example.Foo. For example, you can define a line with 2 points, where each point has an x- and a y-coordinate. Instead ofLine(x1, y1, x2, y2), define aPointclass to represent the points and haveLinetake two instances ofPointas arguments, not 4 numbers: `Line(Point(x1, y1), Point(x2, y2)). There's less room for error when any given value requires fewer arguments to define.