第二十八章 类代码编写细节

时间:2022-05-07 00:58:36
#1.
#A:与C++不同,python的class并不是声明式的,就像def一样,class语句是对象的创建者并且是一个隐含的赋值运算,执行时产生一个类对象

#2.
#A:把简单的非函数对象赋值给类属性,会产生数据属性,由所有实例共享
#B:对实例的属性进行赋值运算会在该实例中创建或修改变量名,而不是在共享的类中
#C:对对象属性进行赋值总是会修改该对象,除此之外没有别的影响
# 例如,y.x会通过继承而在类中查找,而x.spam进行赋值运算则会把该变量名附加在x本身上
#D:继承树的搜索只发生在属性引用时,而不是属性的赋值运算时
#E:将属性附加在类上时,是共享的,附加在实例上时,是独有的
#F:如同函数,对于类和类对象,都可以在外部进行属性添加
class CTest():
value = 10
list0 = [CTest(), CTest()]
value0 = list0[0].value, list0[1].value, CTest.value #value0 = (10, 10, 10)
bValue0 = 'value' in dir(list0[0]), 'value' in list0[0].__dict__ #bValue0 = (True, False)
b0 = list0[0].value is list0[1].value #b0 = True

list0[0].value = 'a' #实际上是list0[0]创建了新属性'value'
value1 = list0[0].value, list0[1].value, CTest.value #value1 = ('a', 10, 10)
bValue1 = 'value' in dir(list0[0]), 'value' in list0[0].__dict__ #bValue1 = (True, True)
b1 = list0[0].value is list0[1].value #b1 = False

CTest.value = 'b'
value2 = list0[0].value, list0[1].value, CTest.value #value2 = ('a', 'b', 'b')
list0[1].value = 'c'
value3 = list0[0].value, list0[1].value, CTest.value #value3 = ('a', 'c', 'b')

CTest.str = 'str'
str = list0[0].str #str = 'str'

#3.
#A:类或者其实例的属性的搜索都是自下而上的
class CFather():
def __init__(self):
self.value = 'Father'
def Fun(self):
return self.action()
class CChild(CFather):
def action(self):
return 'Child'

Child = CChild()
str = Child.Fun() #str = 'Child'
'''
当Child调用函数Fun()的时候,会调用父类的版本,父类的Fun函数又通过self调用action,此时又会进行
由下而上的搜索,从而调用子类的action函数
'''

#4.
#A:raise触发异常
try:
raise ZeroDivisionError
except ZeroDivisionError:
pass #运行至此

#5.
#A:抽象基类的定义
from abc import ABCMeta, abstractmethod
class CTest(metaclass = ABCMeta):
@abstractmethod
def fun(self):
pass
try:
Test = CTest()
except:
pass #运行至此

#6.
#A:dir在python3.0中会收集继承的属性,而__dict__并不会
class CFather():
valueA = 'A'
def __init__(self):
self.value0 = 'Father'
class CChild(CFather):
valueB = 'B'
def __init__(self):
self.value1 = 'Child'
CFather.__init__(self)
str0 = sorted(dir(CChild()), reverse = True)
'''
str0 = ['valueB', 'valueA', 'value1', 'value0', '__weakref__', '__subclasshook__', '__str__', '__sizeof__',
'__setattr__', '__repr__', '__reduce_ex__', '__reduce__', '__new__', '__ne__', ...]
'''

str1 = sorted(dir(CChild), reverse = True)
'''
str1 = ['valueB', 'valueA', '__weakref__', '__subclasshook__', '__str__', '__sizeof__', '__setattr__',
'__repr__', '__reduce_ex__', '__reduce__', '__new__', '__ne__', '__module__', '__lt__', ...]
'''

str2 = CChild().__dict__ #str2 = {'value0': 'Father', 'value1': 'Child'}
str3 = CChild.__dict__
#str3 = mappingproxy({'__init__': <function CChild.__init__ at 0x0000000002E00D90>, '__module__': '__main__', 'valueB': 'B', '__doc__': None})