(公共、私有)类方法、静态方法、实例方法、类属性、实例属性、__call__方法、__del__方法、实例方法的修改与增添:
class Test:
count = 0 #定义公共类属性
company = 'Umbrella Corporation'
__country = 'China' #定义私有类属性
@classmethod #定义类方法之前声明
def printCompany(cls): #定义公共类方法
print('就职公司为{0}'.format(Test.company)) #调用公共类属性
@classmethod
def __printCountry(cls): #定义私有类方法
print('地区为{0}'.format(Test.__country)) #调用私有类属性
@staticmethod #定义静态方法之前声明
def add(a,b): #定义公共静态方法
return a+b
@staticmethod
def __multi(a,b): #定义私有静态方法
return a*b
def __init__(self,name,age):#构造函数
self.__name = name #定义私有实例属性
self.age = age #定义公共类属性
def num(self): #定义公共实例方法
print(Test.count) #调用公共类属性
def __numcount(self): #定义私有实例方法
Test.count += 65
print(Test.count)
def __call__(self,a,b): #定义call方法
print(a+b)
def __del__(self): #定义析构函数
print('程序结束,销毁以下对象:{0}'.format(self))
def num1(s): #将修改实例方法的相关函数
Test.count += 1
print(Test.count)
s1 = Test('Kryser',18) #创建实例对象
def agePrint(s): #将新增的实例方法的相关函数
print('年龄为{0}'.format(s1.age)) #调用公共实例属性
Test.num = num1 #修改num()实例方法
Test.agePrint = agePrint #新增agePrint()实例方法
Test.printCompany() #调用公共类方法 预期打印:就职公司为Umbrella Corporation
Test._Test__printCountry() #调用私有类方法 预期打印:地区为China
print(Test.add(11,88)) #调用公共静态方法 预期打印:99
print(Test._Test__multi(111,9)) #调用私有静态方法 预期打印:999
print(s1._Test__name) #调用私有实例属性 预期打印:Kryser
s1.num() #调用公共实例方法(已经被修改) 预期打印:1
s1._Test__numcount() #调用私有实例方法 预期打印:66
s1(233,322) #调用__call__()方法 预期打印:555
s1.agePrint() #调用新增的agePrint()方法 预期打印:年龄为18
#结束时系统自动调用__del__()方法 预期打印:程序结束,销毁以下对象(对类对象的描述)
结果如图,均符合预期: