Python @ DjangoSpin

Object Oriented Python: Using the __init__() magic method

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Using __init__() in Python

Using __init__() in Python

The __init__ method is one of several class methods which are called implicitly on certain events. These methods are called magic methods, or dunder methods, because of the double underscore in front of the method name. These methods need not be defined, but if defined, Python will execute them on certain events. The __init__() method is called when an instance is created.

The init stands for initialization, as it initializes attributes of the instance. It is called the constructor of a class.

# initializing an instance with static data
>>> class Man:
	def __init__(self):
		self.name = 'Ethan'
		self.age = 10
		self.weight = 60
		self.height = 100
	def details(self):
		print("Hi, I am {}. I am {} years old. I weigh {} lbs and I am {} cm tall.".
			format(self.name, self.age, self.weight, self.height))

		
>>> ethan = Man()
>>> ethan.details()
Hi, I am Ethan. I am 10 years old. I weigh 60 lbs and I am 100 cm tall.


# initializing an instance with dynamic data
>>> class Man:
	def __init__(self, name, age, weight, height):
		self.name = name
		self.age = age
		self.weight = weight
		self.height = height
	def details(self):
		print("Hi, I am {}. I am {} years old. I weigh {} lbs and I am {} cm tall.".
				format(self.name, self.age, self.weight, self.height))

		
>>> ethan = Man('Ethan', 10, 60, 100)
>>> ethan.details()
Hi, I am Ethan. I am 10 years old. I weigh 60 lbs and I am 100 cm tall.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply