Object
Object is having states and behaviors in which state means what does it has and behavior means what does it do. for example a pen has
States: ink, nib, needle, cap etc
Behaviors: Writing.
- Object is an instance of a class.
- Object comprises both data members and methods.
- Object is created from a class.
Class
1.It is a collection of data members and member functions.
2.Data members are the variable used inside class.
3.Member functions are the function used inside class.
4.It is also called Userdefined data type.
5.class keyword is used to create class.
Syntax of class
#creating class class Student: #defining class variables name="Rocky" roll=205
- Here Student is class and name and roll are variables.
- We can create object of class by using class name.
- There is no need of new keyword like java in Python to create object.
- Syntax:
obj_name=class_name()
- For Example:
s1=Student()
Here s1 is object of class Student.
- We can access the variables of class by using dot(.) operator with object.
- We can also access function of a class by using dot(.) operator.
- Example:
#creating class class Student: #defining class variables name="Rocky" roll=205 #creating object s1=Student() #Accessing class variable print("Name:",s1.name) print("Rollno:",s1.roll) """ ***Output*** Name: Rocky Rollno: 205 """
#creating class class Student: #defining class variables name="Rocky" roll=205 marks=85.6 #defining function def showInfo(self): print("Name:", self.name) print("Rollno:",self.roll) print("Marks:",self.marks) #creating object s1=Student() #Calling function of class s1.showInfo() """ ***Output*** Name: Rocky Rollno: 205 Marks: 85.6 """
- Here to access a class variables inside function self keyword is used because self refers to the current class object.
If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other.
Thank you!!...