Class and Instance Attributes in python | Explain class and instance attributes in python | instance attributes Vs class attributes |



Class and Instance Attributes in python  | Explain class and instance attributes in python | instance attributes Vs class attributes |


Class and Instance Attributes

In object-oriented language(OOP), Python provides two attributes:-
1. Instance attributes
2. Class attributes


1. Instance Attributes-

Classes contain characteristics called Attributes. Class refer to a group of homogeneous entities .each entities of class is called object. instance is another name for an object.
An instance attribute is a Python variable and this variable is only accessible in the scope of this object and it is defined inside the constructor function  (Constructor is a special type of method or function which is use to initialize the instance member of class.) __init__(self,..) of the class  i.e instance attribute defined inside the constructor.
The instance attribute is only accessible from the scope of an 
object.


Class and Instance Attributes in python  | Explain class and instance attributes in python | instance attributes Vs class attributes |
Class attributes and instance attributes 






2. Class Attribute -

A class attribute is a Python variable that belongs to a class.
class attribute  defined outside the constructor function, __init__(self,...), of the class. i.e class attribute defined outside the constructor. i.e outside __init__ function .
class attributes shared between all the objects of this class .


basic difference between class attribute and instance attributes is that instance attribute defined inside the constructor function and class attribute defined outside the constructor function.

The class attribute is accessible property of the class as well as  a property of objects, as it is shared between all of them.

Program using instance attributes and class attributed -

class employee:
emp_count=0         # class attributes 
def __init__(self,name,id):
self.name=name #instance attributes
self.id=id                # instance attributes  
employee.emp_count=employee.emp_count+1
def empdata (self):
     print("Name: ",self.name, "ID: ",self.id )
emp1=employee("Bharat",101)     # Object Created 
print("Employee Data :",emp1.empdata())
print("Total Employee: ",employee.emp_count)







Output -

Name:  Bharat ID:  101
Employee Data : None
Total Employee:  1

Post a Comment

Post a Comment (0)

Previous Post Next Post