Labels: Python, Class,Object
Ref:
Python Classes/Objects https://www.tutorialspoint.com/python/python_classes_objects.htm
Classes
- Creating Class
The name of the class immediately follows the keyword class followed by a colon as follow:
class ClassName:
'Optional class documentation string'
class_components
Example
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 displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
__attribute
: Private attribute ('__'
). Not be visible outside the class definition.
- Creating instance objects
# This would create first object of Employee class
emp1 = Employee("Zara", 2000)
- Accessing attributes and functions
emp1.displayEmployee()
print "Total Employee %d" % Employee1.empCount
object._className__attrName.
: Access the private (hided) attributes.
- Attributes accessing functions
Function | Description |
---|---|
getattr(obj, name[, default]) | access the attribute of object. |
hasattr(obj,name) | check if an attribute exists or not. |
setattr(obj,name,value) | set an attribute. If attribute does not exist, then it would be created. |
delattr(obj, name) | delete an attribute. |
Examples:
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'
- Class Built-in Attributes
It can be accessed using dot operator.
Attribute | Description |
---|---|
__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. |
__bases__ |
A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list. |
Example:
class Employee:
'Common base class for all employees'
empCount = 0
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
Result:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees'}
- Class Inheritance
The child class inherits the attributes of its parent class.
A child class can also override data members and methods from the parent.
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
A class from multiple parent classes.
class A: # define your class A
.....
class B: # define your class B
.....
class C(A, B): # subclass of A and B
.....
Check a relationships of two classes and instances:
-
issubclass(sub, sup)
returns true if the given subclass sub is indeed a subclass of the superclass sup. -
isinstance(obj, Class)
returns true if obj is an instance of class Class or is an instance of a subclass of Class -
Methods Overloading
-
Base Overloading Methods
Method | Description | Sample Call |
---|---|---|
__init__(self [,args...]) |
Constructor (with any optional arguments) | obj = className(args) |
__del__( self ) |
Destructor, deletes an object | del obj |
__repr__( self ) |
Evaluatable string representation | repr(obj) |
__str__( self ) |
Printable string representation | str(obj) |
__cmp__ ( self, x ) |
Object comparison | cmp(obj, x) |
网友评论