1, Classes and objects
Example 1
class Employee: 'Base class of employee' 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 # Create the first instance emp1 = Employee("Zhang San", 8000) # Create the second instance emp2 = Employee("Li Si", 15000) emp1.displayEmployee() emp2.displayEmployee() print "Total Employee : %d" % Employee.empCount
Operation result:
Name : Zhang San, Salary : 8000 Name: Li Si, Salary : 15000 Total Employee : 2
analysis:
(1) Init is a constructor. In C++/Java, the constructor name is the same as the class name, while in Python, the constructor name is "init"__
(2) Self, which is equivalent to this in C + + or Java, is a pointer. When an instance is created, self points to the instance
(3) name and salary are instance variables and empCount are class variables
(4) C++/Java needs to use the new keyword to create an instance, Python does not
(5) The second percent sign in the last line, comma in C/C + +
2, Python's built-in class properties
__dict: properties of a class (including a dictionary, which consists of data properties of the class) __doc: the document string of the class __Name: class name __Module: the module where the class definition is located (the full name of the class is' main '. Classname', if the class is in an import module mymod, then the classname. Module is equal to mymod) __bases: all the parent elements of a class (including a tuple of all the parent classes)
Example 2
class Employee: 'Base class of employee' 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 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__
Operation result:
Employee.__doc__: Base class of employee Employee.__name__: Employee Employee.__module__: __main__ Employee.__bases__: () Employee.__dict__: {'displayEmployee': <function displayEmployee at 0x10a93caa0>, '__module__': '__main__', 'empCount': 0, '__doc__': ' Base class of employee ', '__init__': <function __init__ at 0x10a939578>}