Classes
The __init__ method runs when a new object is created.
When we create a class, we can edit the __init__ method.
#Create a new class
class Welcome(object):
def __init__(self):
print("Python Tutorial created a new object")
def hello(self):
print("Hello!")
#Create an object
x = Welcome()
Passing Parameters
The __init__ method can get parameters.
Any parameter that we pass to the object on its creation, is passed to the __init__ method
#Create a new class
class Welcome(object):
def __init__(self, input):
print(input)
def hello(self):
print("Hello!")
#Create an object
x = Welcome("I love Python Tutorial")
Of course we can use this parameters in any of our methods:
#Create a new class
class Welcome(object):
def __init__(self, input):
self.input = input
def hello(self):
print(self.input)
#Create an object
x = Welcome("I love Python Tutorial")
x.hello()
Exercise
- Create a new class
- Add an __init__ method that gets at least 2 inputs
- Create a method the prints out the inputs
#Create a new class
#Create objects
#Print out