Python has been the object-oriented language since day one. Because of this, it is very easy to create and use classes and objects. This chapter will help you with all the improvements in the technique of using Python object-oriented programming.
If you don't have any previous object-oriented (OO) programming experience, then you might want to learn some basic introductory lessons, or at least some form of tutorials that will give you an idea of the basics.
However, there is less introduction to object-oriented programming (OOP):
OOP Terminology Overview
- Class: A user-defined prototype object that defines a set of properties that describe any object of the class. Properties are data members (class variables and instance variables) and methods, accessed through point symbols.
- Class variable: This is a variable shared by all instances of a class. Class variables are defined in the class, but outside of the method definition of any class. Class variables are not used as often as instance variables.
- Data member: A class variable or instance variable that holds the data associated with the class and object.
- Function overloading: The assignment of more than one behavior-specific feature. The type of object (argument) involved in the operation is different.
- Instance variable: A variable within the defined method that belongs only to the current instance of a class.
- Inheritance: The characteristics of a class, that is, the transfer of other classes derived from it.
- Instance: A single object of a class. belongs to the class circle, an Obj object, for example, an instance of a class circle.
- Instantiation: Creates an instance of a class.
- Method: A special function that is defined in a class definition.
- Object: This is the only instance of the data structure defined by its class. An object consists of two data members (class variables and instance variables) and methods.
- Operator overloading: More than one function function, specific operator assignment.
To create a class:
The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon, as follows:
Class ClassName: ' Optional class documentation string ' Class_suite
The Doc__ class has a document string that can be accessed through the class name. __.
Class_suite consists of all defined class members, data properties, and statements of function components.
Example
The following is an example of a simple Python class:
Class Employee: ' Common base class for all employees ' empcount = 0 def __init__ (self, Name, salary): self . Name = Name self.salary = Salary Employee.empcount + = 1 def displaycount (self): print "Total Employee%" D "% Employee.empcount def displayemployee (self): print" Name: ", Self.name,", Salary: ", self.salary
Empcount is a class variable whose value will be shared by all instances of this class. This can be accessed from within a class or from outside, and is accessed in employee.empcount form.
The first method, __init__ (), is a special method that is called by the class constructor or when a new instance of the class is created for the Python invocation of the initialization method.
Declarations are the same as in normal functions, unlike the first parameter to the method in which each method is a class. Python adds a self argument list, and does not need to include the calling method.
To create an instance object:
To create an instance of a class, call the class name and pass any arguments to the __init__ method to receive.
"This would create first object of Employee class" EMP1 = Employee ("Zara", "a") "This would create second object of Employe E class "EMP2 = Employee (" Manni ", 5000)
Access properties:
You can access the properties of an object by using the point operator. The class variable is accessed using the class name, as follows:
Emp1.displayemployee () Emp2.displayemployee () print "Total Employee%d"% Employee.empcount
Now, put all the concepts together:
#!/usr/bin/pythonclass Employee: ' Common base class for all employees ' empcount = 0 def __init__ (self, name, Salary): self.name = name self.salary = Salary Employee.empcount + = 1 def displaycount (self): Print "Total Employee%d"% employee.empcount def displayemployee (self): print "Name:", Self.name, ", Salary:", Self.salary "This would create first object of Employee class" EMP1 = Employee ("Zara", "a") "This would create second OBJEC T of employee class "EMP2 = Employee (" Manni ", Emp1.displayemployee () Emp2.displayemployee () print" Total Employee%d " % Employee.empcount
When the above code is executed, the following results are produced:
Name:zara, Salary:2000name:manni, Salary:5000total Employee 2
You can add, delete, or modify the properties of classes and objects at any time:
Emp1.age = 7 # Add an ' age ' Attribute.emp1.age = 8 # Modify ' age ' attribute.del emp1.age # Delete ' age ' attribute.
In addition to using normal statements to access properties, you can use the following functions:
- GetAttr (obj, name[, default]): Accesses the properties of the object.
- Hasattr (obj,name): Checks if a property exists.
- SetAttr (Obj,name,value): Sets a property. If the property does not exist, it will be created.
- Delattr (obj, name): To delete an attribute.
Hasattr (EMP1, ' age ') # Returns True if ' age ' attribute existsgetattr (EMP1, ' age ') # Returns value of ' age ' Attribu Tesetattr (EMP1, ' age ', 8) # Set attribute ' age ' at 8delattr (Empl, ' age ') # Delete attribute ' age '
Built-in class properties:
Each Python class continues with built-in properties, and they can use the dot operator to access the same as any other property:
- __DICT__: The dictionary contains the namespace of the class.
- __DOC__: The document string for the class, or none if none is defined.
- __NAME__: Class name.
- __MODULE__: The module name that is defined in the class. This property is in interactive mode whose value is "__main__".
- __bases__: A tuple that may be empty contains the base class, in the order in which the base class list appears.
For the class above, try to access these properties:
#!/usr/bin/pythonclass Employee: ' Common base class for all employees ' empcount = 0 def __init__ (self, name, Salary): self.name = name self.salary = Salary Employee.empcount + = 1 def displaycount (self): Print "Total Employee%d"% employee.empcount def displayemployee (self): print "Name:", Self.name, ", Salary:" , Self.salaryprint "employee.__doc__:", Employee.__doc__print "employee.__name__:", Employee.__name__print "Employee . __module__: ", Employee.__module__print" employee.__bases__: ", Employee.__bases__print" Employee.__dict__: ", employee.__dict__
When the above code is executed, the following results are produced:
EMPLOYEE.__DOC__: Common base class for all employeesemployee.__name__: employeeemployee.__module__: __main__employee. __bases__: () employee.__dict__: {' __module__ ': ' __main__ ', ' displaycount ':
, ' Empcount ': 2, ' Displayemployee ':
, ' __doc__ ': ' Common base class for all employees ', ' __init__ ':
}
Destroying objects (garbage collection):
Python removes unwanted objects (built-in types or instances of classes), freeing up memory space automatically. The process of using chunks of memory that are recycled periodically by Python is called garbage collection.
The Python garbage collector runs during program execution when the reference count of an object is zero. The reference count of an object changes to point to the number of aliases it changes.
When it assigns a new name or an object that is placed in a container (list, tuple or dictionary) the reference count is incremented. When the object's reference count is reduced by using del Delete, its datum is reassigned, or its references are out of range. When the reference count of an object changes to 0, Python automatically collects it.
A = + # Create Object <40>b = a # increase ref. Count of <40> C = [b] # Increase ref. Count of &L T;40> del a # decrease ref. Count of <40>b = # Decrease Ref. Count of <40> c[0] = 1
When the garbage collector destroys orphaned instances and reclaims its space, it is generally not noticed. However, a class can implement a special method __del__ (), called when the destructor is called, and the instance is destroyed. This method can be used to clean up any non-memory resources that are used by an instance.
Example:
The __del__ () destructor prints an instance of the class name that it is about to be destroyed:
#!/usr/bin/pythonclass point: def __init (self, x=0, y=0): self.x = x self.y = y def __del__ (self): class_name = self.__class__.__name__ print class_name, "destroyed" PT1 = Point () pt2 = PT1PT3 = Pt1print ID (pt1) , ID (PT2), id (PT3) # Prints the IDs of the Obejctsdel Pt1del Pt2del pt3
When executing the above code, it produces the following result:
Note: Ideally, you should define a separate file for the class, and you should import it into the main program file using the import statement. See the python-Module section for more details on importing modules and classes.
Class Inheritance:
Instead of starting from scratch, you can derive a class from an existing class by deriving it from the new class name of the parent class of the parentheses listed above.
Subclasses inherit the properties of the parent class, and can use these properties of the parent class as if they were defined in the subclass. Subclasses can also overwrite the data members and methods of the parent class.
Grammar
The declarations of derived classes are much like their parent classes; From the list of base classes, give the class name inheritance:
Class Subclassname (parentclass1[, ParentClass2, ...]): ' Optional class documentation string ' Class_suite
Example
#!/usr/bin/pythonclass Parent: # define parent class parentattr = def __init__ (self): print " Calling parent Constructor " def Parentmethod (self): print ' calling parent method ' def setAttr (self, attr): parent.parentattr = attr def getAttr (self): print ' Parent attribute: ', Parent.parentattrclass child ( Parent): # define child class def __init__ (self): print ' calling child constructor ' def childmethod (self ): print ' calling child method ' C = Child () # Instance of Childc.childmethod () # Child calls its Methodc.par Entmethod () # calls Parent's methodc.setattr (s) # again call parent's methodc.getattr () # again call Parent ' s method
When the above code is executed, the following results are produced:
Calling child constructorcalling child methodcalling parent Methodparent attribute:200
In a similar way, you can inherit classes from more than one parent class as follows:
Copy the Code code as follows:
Class A: # define your Class A
.....
Class B: # define your CALSS b
.....
Class C (A, B): # Subclass of A and B
.....
You can use the Issubclass () or isinstance () function to examine the relationship of two classes and instances.
- Issubclass (Sub, SUP) if the given subclass is indeed a subclass of the Super SUP, the Boolean function returns True.
- Isinstance (obj, Class) If obj is an instance of class, or is an instance of a subclass of a class Boolean function returns True
Override method:
Methods that can override the parent class. One of the reasons to override the parent's method is because you might want to special in subclasses or implement different functions.
Example
#!/usr/bin/pythonclass Parent: # define parent class def myMethod (self): print ' calling parent Method ' class child (Parent): # define child class def myMethod (self): print ' calling child method ' C = child () # Instance of Childc.mymethod () # Child calls overridden method
When the above code is executed, the following results are produced:
Calling child method
Base Overloaded methods:
The following table lists some common features that can be overridden in a class:
Overloaded operators:
Suppose you want to create a vector class to represent a two-dimensional vector, and when you use the Add operator to increase what happens to them? Most likely the python will dick you.
Yes, but defining the __add__ method adds vector additions to the class, plus the behavior of the operator as expected:
Example:
#!/usr/bin/pythonclass Vector: def __init__ (self, A, b): SELF.A = a self.b = b def __str__ (self): Return ' vector (%d,%d) '% (SELF.A, self.b) def __add__ (self,other): return vector (SELF.A + other.a, self.b + othe r.b) v1 = vector (2,10) v2 = vector (5,-2) Print V1 + v2
When the above code is executed, the following results are produced:
Vector (7,8)
Data hiding:
The properties of an object can be or may not be visible outside the class definition. For these cases, you can name the double underscore prefix attribute, which cannot be directly externally visible.
Example:
#!/usr/bin/pythonclass justcounter: __secretcount = 0 def count (self): Self.__secretcount + 1 Print Self.__secretcountcounter = Justcounter () counter.count () Counter.count () print Counter.__secretcount
When the above code is executed, the following results are produced:
12Traceback (most recent call last): File "test.py", line page, in
print Counter.__secretcountattributeerror: Justcounter instance has no attribute ' __secretcount '
The protection members of Python change the name internally to include the class name. These properties can be accessed through object._classname__attrname. If you want to change the last line, then it will work as follows:
.......... print Counter._justcounter__secretcount (.....)
When the above code is executed, the following results are produced:
122