#############面向对象#####################
类:
In [1]: class MyClass(object): ##用class定义一个类 ...: def pstar(self): ...: print '*'*20 ...: In [2]: a = MyClass() ##创建一个实例对象,跟java相似 In [3]: a.pstar() ##通过实例对象,调用类里面的方法,这里的相当于把实例对象’a‘传递给self,作为pstar的参数了,所以不报错,self 是可以是任何东西,习惯写self ********************
In [4]: MyClass.pstar(a) #####
********************
#####################类的组合###########################
#!/usr/bin/env python #-*- coding:utf-8 -*- class Info(object): def __init__(self,ph,em,qq): self.phone = ph self.email = em self.qq = qq def get_phone(self): return self.phone def update_phone(self,newph): self.phone = newph class AddrBook(): def __init__(self,nm,ph,em,qq): self.name = nm self.info = Info(ph,em,qq) if __name__ == '__main__': bob = AddrBook("Bob Green",'15980113980','bob@qq.com','12345678') print bob.info.get_phone()
效果:
C:Python27python2.exe D:/pycharm/pa/addbook2.py 15980113980 Bob Green
####################类的继承###################
#!/usr/bin/env python #-*- coding:utf-8 -*- class AddBook(object): def __init__(self,nm,ph): self.name = nm self.phone = ph def get_name(self): return self.name def get_phone(self): return self.phone class Add(AddBook): pass if __name__ == '__main__': bob = Add('Bob Green','15980113990') print bob.get_phone() print bob.get_name()
效果:
C:Python27python2.exe D:/pycharm/pa/addbook.py 15980113990 Bob Green
#!/usr/bin/env python #-*- coding:utf-8 -*- class AddBook(object): def __init__(self,nm,ph): self.name = nm self.phone = ph def get_name(self): return self.name def get_phone(self): return self.phone class Add(AddBook): def __init__(self,nm,ph,id): self.id = id AddBook.__init__(self,nm,ph) #####继承 if __name__ == '__main__': bob = Add('Bob Green','15980113990','350823199900616671') print bob.get_phone() print bob.get_name() print bob.id
效果:
C:Python27python2.exe D:/pycharm/pa/addbook.py 15980113990 Bob Green 350823199900616671
额外:
##########__str__##############
#!/usr/bin/env python #-*- coding:utf-8 -*- class Book(): def __init__(self,tt,bb): self.tt = tt self.bb = bb def __str__(self): return self.tt if __name__ == '__main__': playbook = Book('fush','hua') print playbook ###因为类中定义了__str__方法,直接通过实例对象返回值
结果:
C:Python27python2.exe D:/pycharm/pa/book.py
fush
############__call__################
#!/usr/bin/env python #-*- coding:utf-8 -*- class Book(): def __init__(self,tt,bb): self.tt = tt self.bb = bb def __str__(self): return self.tt def __call__(self): print '%s %s' % (self.tt,self.bb) if __name__ == '__main__': playbook = Book('fush','hua') print playbook #因为类中定义了__str__方法,此处打印出的是__str__的返回值 playbook() #调用playbook就是执行__call__方法中的代码
今日最后:
In [8]: import ftplib In [9]: ftplib.__file__ Out[9]: '/usr/lib64/python2.6/ftplib.pyc'
[root@master ~]# vim /usr/lib64/python2.6/ftplib.py