Objects:
In Python, everything is an object. we can use type() to check the type of object. We can create our own Object type using class keyword.
print(type(1)) # < class 'int' >
print(type([])) # < class 'list' >
print(type(())) # < class 'tuple' >
print(type({})) # < class 'dict' >
Class:
- class is a blueprint that defines the nature of an object. It is created using the class keyword. We need to use the .(dot) notation to use the attributes (class variables and instance variables) and method of the class object.
- By convention we give classes a name that starts with a capital letter.
- attribute :is a characteristic of an object.
- method :is an operation we can perform with the object.
- Instance variable : A variable that is defined inside a method and belongs only to the current instance of a class.
- Instantiation : The creation of an instance of a class.
# Create a new object type called Sample
class Sample:
pass
# Instance of Sample
x = Sample()
print(type(x)) # < class '__main__.Sample' >
Class object attributes
- Class Object Attributes hold the same value for any instance of the class.
- It is defined outside of any methods in the class. Also by convention, we place them before the __init__() method.
Methods
- Methods are functions defined inside the body of a class.
- It is used to perform operations with the attributes of our objects.
class Employee:
empCount = 0 # Class Object Attributes
def __init__(self, name, salary):
self.name = name # An attribute of Employee
self.salary = salary # An attribute of Employee
Employee.empCount += 1
def empDetails(self): # method of Employee Class
print("Name : {} Salary : {}".format(self.name,self.salary)
__init_ method :
- __init__ method is used to initialize the attributes of an object.
- It is automatically called right after the object has been created.
class Employee:
'Employee base class, containing basic info. of employee'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def empDetails(self):
print("Name : {} , Salary : {}".format(self.name,self.salary)
self Parameter in Python :
- The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
- self must be provided as a First parameter to the Instance method and constructor. If we don’t provide it, it will cause an error.
- It does not have to be named self , we can call it whatever we like.
Creating Instance Objects
To create instances of a class, we call the class using class name and pass the prameter as per its __init__ method.
# Creating Instance Object of Employee Class:
employee1 = Employee("Sameer", 50000)
employee2 = Employee("Rajeev", 9000)
Accessing Attributes:
We can access the object's attributes using the dot operator with object. Class variable can be accessed using class name directly.
# Creating Instance Object of Employee Class:
employee1.empDetails()
employee2.empDetails()
print("Total Employee : {}".format(Employee.empCount))
# Output :
Name : Sameer , Salary : 50000
Name : Rajeev , Salary : 9000
Total Employee : 2
Methods to acces attributes :
- getattr(obj, name[, default]) - to access the attribute of an object.
- hasattr(obj,name) - to check if an attribute exists or not.
- setattr(obj,name,value) - to set an attribute. If attribute does not exist, then it would be created.
- delattr(obj, name) - to delete an attribute.
getattr(employee1, 'name') # Returns value of 'name' attribute
hasattr(employee1, 'name') # Returns true if 'name' attribute exists otherwise returns false
setattr(employee1, 'name', "Raman") # Set attribute 'name' to Raman
delattr(employee1, 'name') # Delete attribute 'name'
Add, remove, or modify attributes of classes and objects :
# Add
employee1.empCode = 'JZADF123'
# Modify
employee1.empCode = 'JUYDFDK1'
# Delete
del employee1.empCode
Built-in Class Attributes :
- __bases__ A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
- __dict__ Dictionary containing the class's namespace.
- __doc__ Class documentation string or none, if undefined.
- __module__ Module name in which the class is defined. This attribute is "__main__" in interactive mode.
- __name__ name of the class.
print("Employee1.__bases__ : {}".format(Employee1.__bases__)) # Output: Employee1.__bases__ : ()
print("Employee1.__dict__ : {}".format(Employee1.__dict__))
print("Employee1.__doc__ : {}".format(Employee1.__doc__)) # Output: Employee1.__doc__ : Employee base class, containing basic info. of employee
print("Employee1.__module__ : {}".format(Employee1.__module__)) Output: Employee1.__module__ : __main__
print("Employee1.__name__ : {}".format(Employee1.__name__)) Employee1.__name__ : Employee
Special Methods :
- __init__()
- __str__()
- __len__()
- __del__()