Beginning Python - Chapter6 : More Abstraction

#Chapter5:more abstraction

#1 The magic of objects
# polymorphism means having multiple forms.
# encapsulation
# inheritance

#2 making your own classes
class Person:
    def setName(self,name):
        self.name=name
    def setPrint(self):
        print "hello, %s " % self.name
c1 = Person()
c1.setName('lili')
c1.setPrint()

#3 attributes,fuctions,and methods
class Class:
    def method(self): #must have self, distinguish with function
        print "self"
def function():
    print 'function'
instance = Class()
instance.method()
function()
function = instance.method
function()
#instance.method = function
#instance.method()

#4 privacy revisited
class Test:
    __name = 'lili'   #__ cannot be accessed ,same with method
    nameCopy = __name
    no=100
t = Test()
# print t.name wrong (Test instance has no attribute 'name')
print '-----'
print t._Test__name # way to access private data(method)
print t.no
print t.nameCopy

#5 the class namespace
# inter param exists in one namespace,can be kept
class Test:
    num = 1
    num1 = 2
    def init(self): #attention self,must use self
        self.num +=2
        self.num1*=2
        return self.num,self.num1
t1 = Test()
t2 = Test()
print t1.init(),t1.num1 #3,4
print t1.init(),t1.num1 #5,8
print t2.init(),t2.num1 #3,4
print t2.init(),t2.num1 #5,8

#6 specifying a superclass
class super1:
    def init(self):
        print "-super"
    def copy(self):
        print "-copy-super1"
class sub1(super1):
    def copy(self):
        print "-copy-sub1"

s = sub1()
s.init()    #-copy-super1
s.copy()    #-copy-sub1

#7 investigating inheritance

# -- issubclass(sub,super)
# find out whether a class is a subclass of another
print issubclass(sub1,super1)   #True
print issubclass(Test,super1)   #False

# -- __bases__
# find out its base calsses
print sub1.__bases__ #(<class __main__.super1 at 0x015BF538>,)
print super1.__bases__ #()

# -- isinstance(instance,class)
print isinstance(s,sub1)    #True
print isinstance(s,super1)  #True
print isinstance(s,Test)    #False

#8 mutiple superclasses
class super1:
    pass
class super2:
    pass
class sub(super1,super2):
    pass

#9 Interfaces and Introspection
# waiting P181
# interface

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值