#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