class calculate:
def add(self,abc): # self is a boilerplate when using classes
a=abc+1
print(a)
cal=calculate() #Define the class calculate as cal.
cal.add(10) # Call the add function in the class. Assign 10 to abc.
→ 11
cal=calculate().add(10) # This way of writing is also fine. However, it will only be called once.
→ 11
<Example 2: Define multiple defs in a class>
In Example 1, you can use just def without defining a class.
The advantage of using classes is that variables created with def can be used by different functions within the class, as shown below.
class calculate:
def add(self):
self.a=1+1 # The variable can be used in other functions by setting it as "self".
print(self.a)
def sub(self):
b=self.a-1
print(b)
cal=calculate()
cal.add()
cal.sub()
→ 2
1
<Example 3: Define the initial value>
Define the initial value as follows:
class calculate:
def __init__(self, c): # Initial value assignment function
self.c = c
self.d = 20
def add(self,d):
self.a=self.c+d
print(self.a)
def sub(self):
b=self.a-1
print(b)
cal=calculate(10) # Assign 10 to c in the initial value assignment function
print(vars(cal))
→ {'c': 10, 'd': 20} # print(cal.c) prints only c
cal.add(5) # Assign 5 to the variable d in the add function
class calsub(caladd):# Define the initial value of the caladd class
def sub(self):
super(calsub,self).add(5) # Executes the add function of caladd. calsub and self can be omitted.
b=self.a-1
print(b)
cal=calsub(10) # Assign 10 to the initial value of the caladd class
cal.sub()