class Employee:
'Base class of employee'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def showInfo(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.showInfo()
emp2.showInfo()
print "Total Employee : %d" % Employee.empCount
运行结果:
Name : Zhang San, Salary : 8000
Name: Li Si, Salary : 15000
Total Employee : 2
分析:
(1)__init__
是构造函数。C++/Java中的构造函数名和类名一样,而Python的构造函数名为__init__
(2)self相当于C++或Java中的this, 是一个指针。当创建一个实例后,self指向该实例
(3)name和salary是实例变量,empCount是类变量
(4)C++/Java创建实例需要使用new关键字,Python不需要
(5)最后一行的第二个百分号,相当于C语言printf中的逗号
__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
__bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
class Employee:
'Base class of employee'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def showInfo(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__
运行结果:
Employee.__doc__: Base class of employee
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__:
{'showInfo': <function showInfo at 0x10a93caa0>,
'__module__': '__main__',
'empCount': 0,
'__doc__': ' Base class of employee ',
'__init__': <function __init__ at 0x10a939578>}
Python 使用了引用计数这一技术来跟踪和回收垃圾。 在 Python 内部记录着所有使用中的对象各有多少引用。 一个内部跟踪变量,称为一个引用计数器。
当对象被创建时, 就创建了一个引用计数, 当这个对象不再需要时, 也就是说, 这个对象的引用计数变为0 时, 它被垃圾回收。但是回收不是"立即"的, 由解释器在适当的时机,将垃圾对象占用的内存空间回收。
import sys
class 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()
print sys.getrefcount(pt1)
pt2 = pt1
print sys.getrefcount(pt1)
pt3 = pt2
print sys.getrefcount(pt1)
del pt3
print sys.getrefcount(pt1)
del pt2
print sys.getrefcount(pt1)
del pt1
运行结果:
2
3
4
3
2
Point Destroyed!
分析:
pt1 = Point(),等号右侧创建了一个对象,引用计数为1;等号左侧让引用pt1指向这个对象,引用计数加1变为2
pt2 = pt1,引用计数加1 变为3
pt3 = pt1,引用计数加1 变为4
del pt3,引用计数减1变为3
del pt2, 引用计数减1变为2
del pt1,引用计数减1,同时因为最初创建的对象没用引用指向他,对象会被释放,引用计数再减去1,变为0。析构函数__del__
被调用。
注意,因为引用计数为0,所以不能用 print sys.getrefcount(pt1)来查看引用计数。若查看会抛出异常。