A class
is a user-defined prototype, from which objects
can be created. Classes
can bundle data
and functions
together.
An object
is an instance of a class
. When an object
is created, the class
is said to be instantiated.
How to define a simple class?
The following is an example of defining a class
in Python and its output.
class A_simple_class:
variable_0= 5
print(A_simple_class)
<class '__main__.A_simple_class'>
How to define an object?
The following is the syntax for defining an object
.
Object_Name = Class_Name()
Object_0 = A_simple_class()
print(Object_0.variable_0)
5
How to define a class
with functions?
We can add two functions
within a class
when defining the class
. The following is the code example and output.
class Tesla:
def fun1(model):
print('This is a', model)
def fun2(year):
print(f"This model is {year}")
car_1=Tesla
car_1.fun1("Model 3")
car_1.fun2(2021)
This is a Model 3 This model is 2021
How to use the __init__ in defining a class?
You can also add __init__()
in the definition of a class. The following is the code example and output. You can compare it with the example shown above. While they generate the same output, the codes are slightly different.
class Tesla:
def __init__(self,model, year):
# the following defines instance variables
self.model=model
self.year=year
# instance method / object method
def fun1(self):
print('This is a', self.model)
# instance method / object method
def fun2(self):
print(f"This model is {self.year}")
# create an object from the class
t_0=Tesla("Model 3",2021)
# call methods
t_0.fun1()
t_0.fun2()
This is a Model 3 This model is 2021
How to modify instance variables and class variables?
The following code example shows how to modify instance variables
and object variables
.
class Tesla:
# class variable
Factory_name='Fremont'
# constructor
def __init__(self,model, year):
# the following defines instance variables
self.model=model
self.year=year
# instance method / object method
def fun1(self):
print('This is a', self.model)
# instance method / object method
def fun2(self):
print(f"This model is {self.year}")
# create an object from the class
t_0=Tesla("Model 3",2021)
print("Before Modification:")
print(t_0.model)
print(t_0.Factory_name)
print("\n")
# modify object variables
t_0.model='Model Y'
t_0.Factory_name='Texas'
print("After Modification:")
print(t_0.model)
print(t_0.Factory_name)
Before Modification: Model 3 Fremont After Modification: Model Y Texas