Python Class
Introduction
In this chapter, we will learn to use Python Class.
Class
- Firstly open python terminal and in Command Prompt of Windows and write code as below:
- self.name=name
- self.age=age
- self.grade = grade
- Now make Object of class and insert a value of Student like below:
- __dict__: Dictionary containing the class's namespace.
- __doc__: Class documentation string or none, if undefined.
- __name__: Class name.
- __module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode.
- __dict__: A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
- Now we example of all the above attributes.
- print(Student.__doc__)
- print(Student.__name__)
- print(Student.__module__)
- print(Student.__bases__)
- print(Student.__dict__)
- Creation and Deletion of Object is easy in python as below code:
- Student1 = Student("A",1,"A") // create student1 object
- Student2 = Student("B",2,"B") // “”
- del Student1 // delete the object student1
- del Student2 //””
- def __init__(self,name,age,grade):
a. self.name=nameb. self.age=agec. self.grade = grade - def displayStudent(self):
a. return ("Student name is "+self.name+" and age is "+str(self.age)) - student1=Student("BOB",21,"A")
- student1.displayStudent()
-
• getattr(obj, name[, default]) : to access the attribute of object.
• hasattr(obj,name) : to check if an attribute exists or not.
• setattr(obj,name,value) : to set an attribute. If the attribute does not exist, then it would be created.
• delattr(obj, name) : to delete an attribute - Let's take an example of these Methods
class Student:
- def __init__(self,name,age
- self.name=name
- self.age=age
- self.grade = grade
- Student1 = Student("A",21,"A")
- hasattr(Student1,"age")
- hasattr(Student1,"marks")
- setattr(Student1,"marks","75")
- hasattr(Student1,"marks")
- getattr(Student1,"grade")
- getattr(Student1,"name")
- delattr(Student1,"marks")
- hasattr(Student1,"marks")
- def __init__(self,name,age
Conclusion
In the next chapter, you will learn about inheritance in Python.
Author
Neeraj Kumar
0
8.1k
2.3m