import sys
class TestClass(object):
#定义类属性和私有类属性
__name="wei"
name="whb"
def __init__(self):
#实例属性不能这样定义
#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):#需要默认参数cls
print("classmethod worked")
tc1=TestClass()
print(sys.getrefcount(tc1))
tc2=TestClass()
类定义的外部访问不了类的私有属性
print(tc1.__name)
TestClass.__name
类定义的外部访问不了类的私有方法,可以调用封装了私有方法的方法
tc1.__fun()
TestClass.__fun()
tc1.packPrivateFun()
修改实例对象的类属性并对比类的类属性
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)
调用类方法
tc1.happy(0)
TestClass.happy(0)