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"
運行結果:
Name : Zhang San, Salary : 8000
Name: Li Si, Salary : 15000
Total Employee : 2
分析:
(1)__init__
是構造函數.C++/JavaThe constructor name in is the same as the class name,而Python的構造函數名為__init__
(2)self相當於C++或Java中的this, 是一個指針.when an instance is created,self指向該實例
(3)name和salary是實例變量,empCount是類變量
(4)C++/Java創建實例需要使用new關鍵字,Python不需要
(5)The second percent sign on the last line,相當於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 A technique called reference counting is used to track and collect garbage.
在 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
運行結果:
2
3
4
3
2
Point
分析:
pt1 = Point(),An object is created to the right of the equal sign,引用計數為1;Let the left side of the equal sign quotept1指向這個對象,引用計數加1變為2
pt2 = pt1,引用計數加1 變為3
pt3 = pt1,引用計數加1 變為4
del pt3,引用計數減1變為3
del pt2, 引用計數減1變為2
del pt1,引用計數減1,Also because the initially created object has no reference to it,對象會被釋放,The reference count is then subtracted1,變為0.析構函數__del__
被調用.
注意,因為引用計數為0,所以不能用 print sys.getrefcount(pt1)to see the reference count.If checked, an exception will be thrown.
更多內容請關注微信公眾號