Why don’t we have init() method in the second class?

Why don’t we have init() method in the second class? Is it possible to have classes without this method? When it is nessessary and when it isn’t? Kinda tricky thing

Any defined class can be instantiated.

>>> class Foo:
	pass

>>> bar = Foo()
>>> isinstance(bar, Foo)
True
>>> type(bar)
<class '__main__.Foo'>
>>> 

That tells us that no methods or attributes are required. Total design freedom.

It comes with a larger role, of course, which is to write cookie cutters that give us a clearer picture on everything, especially when multiple instances are in play.

We can use a class structured on data alone, or methods alone, which is something to wrap one’s head around. I’m still intimidated by classes even while I think I understand them.

Think of a class where we can hand off an identical populated slate of variables and data to every instance. Using another class we can give each of those instances an identical set of methods that let them evolve from the moment of their instantiation and become unique objects.

Takes a minute. There is more to this question that deserves examination, but I’ll leave it here.

>>> class Foo:
	a = 1
	b = 2
	c = 3

	
>>> bar = Foo()
>>> bar.a
1
>>> baz = Foo()
>>> baz.c
3
>>> baz.c += baz.b
>>> baz.c
5
>>> 

Get ready…

>>> class Faz(Foo):
	def adda(self, other):
		return self.a + other.a
	def addb(self, other):
		return self.b + other.b
	def addc(self, other):
		return self.c + other.c

	
>>> bar = Faz()
>>> baz = Faz()
>>> Faz.adda(bar, baz)
2
>>> Faz.addb(bar, baz)
4
>>> Faz.addc(bar, baz)
6
>>> 
2 Likes

Would you say that the purpose of __init__(self) is to define parameters for the class during instantiation? To @darkse1d’s question, a subclass would require an init method if it had extra parameters?

The method is to a Python class what a constructor method is to a JavaScript class. It permits input parameters to set the initial state of the new instance, so yes, it would be required in that case. My main point above is that it is not a black and white rule, but a feature of OOP.

1 Like

Should a subclass have an attribute that overwrites the parent class attribute, __init__() would be one way to do it. But it is not the only way. The subclass could overwrite the parent values for existing variables. It’s in exploring classes without initialization that we discover nuances that might not ever be evident if we don’t. Toss the rule book. There isn’t one when it comes to exploration. See what promises the language keeps, and go from there.

1 Like