Classes
Class is an object constructor. An object is an instance of a class. The class is used to define the properties and behavior (the methods), and then it can be used to create many instances (objects) of that class.
Create a New Class
#Create a new class
class Welcome(object):
def hello(self):
print("Hello!")
We created a class with the name Welcome. Welcome has a method named hello.
Method - a function that operates on a specific class.
Self - is the first parameter in every method of a class. Self says that the method operates on the object itself.
How to Create an Object
We simply assign the object to a variable.
#Create a new class
class Welcome(object):
def hello(self):
print("Hello!")
#Create an object
x = Welcome()
x.hello()
x is an instance of the class Welcome.
We can create as many instances as we want!
#Create a new class
class Welcome(object):
def hello(self):
print("Hello!")
#Create an object
x = Welcome()
y = Welcome()
print(type(x) == type(y))
print(type(x) is Welcome)
print(type(x) == Welcome)
Exercise
- Create a new class
- Add a method to the class
- Create a few instances of the class
#Create a new class
#Create objects