码迷,mamicode.com
首页 > 其他好文 > 详细

第三十章 类的设计

时间:2017-04-29 10:59:44      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:div   语句   als   pytho   显示   划线   没有   地址   str   

#1.
#A:变量名压缩:class语句内开头有两个下划线,但是结尾没有的变量名会自动扩张,如CA类的__X变量会自动扩张为_CA__X
#B:变量名压缩只发生在class内,而且只针对于开头有两个下划线的变量,包括方法和实例属性
class CTest():
    def __init__(self):
        self.__value = ‘a‘
    def __Fun(self):
        return self.__value
Test = CTest()
v0 = Test._CTest__value             #v0 = ‘a‘
v1 = Test._CTest__Fun()             #v1 = ‘a‘
#v2 = Test.__value                  #运行出错
#v3 = Test.__Fun()                  #运行出错

#2.
#A:子类在父类中的搜索是从左到右的
#B:对于大型项目来说,变量名压缩可以起到防止变量名冲突的作用
class CFather0():
    def __init__(self):
        self.__value0 = ‘Father0_0‘
        self.value1 = ‘Father0_1‘
class CFather1():
#由于子类在父类中的搜索时从左到右的,而子类若没有显示调用__init__构造函数,则此构造函数不会被调用
    def __init__(self):
        self.__value0 = ‘Father1_0‘ 
        self.value1 = ‘Father1_1‘
class CChild(CFather0, CFather1):pass
Child = CChild()
v0 = Child.value1                   #v0 = ‘Father0_1‘
v1 = Child._CFather0__value0        #v1 = ‘Father0_0‘
#v2 = Child._CFather1__value0

class CChild(CFather0, CFather1):
    def __init__(self):
        CFather0.__init__(self)
        CFather1.__init__(self)
Child = CChild()
#由于CFather1的构造函数调用晚于CFather0,所以Child.value1调用的是CFather1中的变量value1
v0 = Child.value1                   #v0 = ‘Father1_1‘
v1 = Child._CFather0__value0        #v1 = ‘Father0_0‘
v2 = Child._CFather1__value0        #v2 = ‘Father1_0‘

#3.
#A:type(), isinstance()
value = 10
str = ‘a‘
b0 = type(value) == int             #b0 = True          
t0 = type(value)                    #t0 = <class ‘int‘>

class A:
    pass
class B(A):
    pass
b0 = isinstance(A(), A)             #b0 = True
b1 = type(A()) == A                 #b1 = True
b2 = isinstance(B(), A)             #b2 = True
b3 = type(B()) == A                 #b3 = False

#4.
#A:id()可以显示对象的内存地址
value0 = 1
value1 = 1
v0 = id(value0)                     #v0 = 0x55aeb6b0
v1 = id(value1)                     #v0 = 0x55aeb6b0

  

第三十章 类的设计

标签:div   语句   als   pytho   显示   划线   没有   地址   str   

原文地址:http://www.cnblogs.com/szn409/p/6784488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!