import sys
class TestClass(object):
#定義類屬性和私有類屬性
__name="wei"
name="whb"
def __init__(self):
#實(shí)例屬性不能這樣定義
#self.__salary=8000
self.salary=8000
self.id=556600
def __str__(self):
return "TestClass Description"
def __del__(self):
pass
#print("TestClass instance is destroyed")
def __new__(cls):
#print("TestClass instance is created")
return object.__new__(cls) #需要return
def __fun(self):
print("private function")
#將私有方法封裝
def packPrivateFun(self):
pass
self.__fun()
@classmethod
def happy(cls,arg):#需要默認(rèn)參數(shù)cls
print("classmethod worked")
tc1=TestClass()
print(sys.getrefcount(tc1))
tc2=TestClass()
類定義的外部訪問不了類的私有屬性
print(tc1.__name)
TestClass.__name
類定義的外部訪問不了類的私有方法,可以調(diào)用封裝了私有方法的方法
tc1.__fun()
TestClass.__fun()
tc1.packPrivateFun()
修改實(shí)例對(duì)象的類屬性并對(duì)比類的類屬性
tc1.name="xia"
tc2.name="lu"
print(tc1.name)
print(tc2.name)
print(TestClass.name)
修改類的類屬性
TestClass.name="all"
tc3=TestClass()
print(TestClass.name)
print(tc3.name)
print(tc1.name)
print(tc2.name)
調(diào)用類方法
tc1.happy(0)
TestClass.happy(0)