class MyFirstClass:
def __init__(self, name):
self.name = name
def greet(self):
print('Hello {}!'.format(self.name))
my_instance = MyFirstClass('John Doe')
print('my_intance: {}'.format(my_instance))
print('type: {}'.format(type(my_instance)))
print('my_instance.name: {}'.format(my_instance.name))
The functions inside classes are called methods. They are used similarly as functions.
alice = MyFirstClass(name='Alice')
alice.greet()
__init__()¶__init__() is a special method that is used for initialising instances of the class. It's called when you create an instance of the class.
class Example:
def __init__(self):
print('Now we are inside __init__')
print('creating instance of Example')
example = Example()
print('instance created')
__init__() is typically used for initialising instance variables of your class. These can be listed as arguments after self. To be able to access these instance variables later during your instance's lifetime, you have to save them into self. self is the first argument of the methods of your class and it's your access to the instance variables and other methods.
class Example:
def __init__(self, var1, var2):
self.first_var = var1
self.second_var = var2
def print_variables(self):
print('{} {}'.format(self.first_var, self.second_var))
e = Example('abc', 123)
e.print_variables()
Class variables are shared between all the instances of that class whereas instance variables can hold different values between different instances of that class.
class Example:
# These are class variables
name = 'Example class'
description = 'Just an example of a simple class'
def __init__(self, var1):
# This is an instance variable
self.instance_variable = var1
def show_info(self):
info = 'instance_variable: {}, name: {}, description: {}'.format(
self.instance_variable, Example.name, Example.description)
print(info)
inst1 = Example('foo')
inst2 = Example('bar')
# name and description have identical values between instances
assert inst1.name == inst2.name == Example.name
assert inst1.description == inst2.description == Example.description
# If you change the value of a class variable, it's changed across all instances
Example.name = 'Modified name'
inst1.show_info()
inst2.show_info()