InterviewSolution
| 1. |
How do you create a class in Python? |
|
Answer» To create a class in python, we use the keyword “class” as shown in the example below: class InterviewbitEmployee: def __init__(SELF, emp_name): self.emp_name = emp_nameTo instantiate or create an object from the class created above, we do the following: emp_1=InterviewbitEmployee("Mr. Employee")To access the name attribute, we just call the attribute using the DOT operator as shown below: print(emp_1.emp_name)# Prints Mr. EmployeeTo create methods inside the class, we include the methods under the scope of the class as shown below: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name def introduce(self): print("Hello I am " + self.emp_name)The self parameter in the init and introduce functions represent the reference to the CURRENT class instance which is used for accessing attributes and methods of that class. The self parameter has to be the first parameter of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed as shown below: emp_1.introduce()class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name def introduce(self): print("Hello I am " + self.emp_name) # create an object of InterviewbitEmployee classemp_1 = InterviewbitEmployee("Mr Employee")print(emp_1.emp_name) #print employee nameemp_1.introduce() #introduce the employee |
|