python學習-OOP

來源:互聯網
上載者:User
#!/usr/bin/env python#-*- coding:utf-8 -*-'Class Define'__author__ = 'hui.qian'class Student(object):    def __init__(self,name,score):        self.name = name        self.score = score    def print_score(self):        print '%s:%s'%(self.name,self.score)bart = Student('hui.qian',90)lisa = Student('zuomu.qian',78)bart.print_score()lisa.print_score()class Student1(object):    passqian = Student1()print qianqian.name = 'hui'print qian.name'訪問限制'#在變數前加2個底線,變數就變成privateclass Student2(object):    def __init__(self,name,score):        self.__name = name        self.__score = score    def print_score(self):        print '%s:%s'%(self.__name,self.__score)    def get_name(self):        return self.__name    def get_score(self):        return self.__scorehui = Student2('hui.qian','85')hui.print_score()print hui.get_name()print hui.get_score()'繼承和多態'class Father(object):    def call_father(self):        print 'daddy'    class Son(Father):    def print_name(self):        print 'I\'m your son '    def call_father(self):        print 'daddy:'class Daughter(Father):    def print_name(self):        print 'I\'m your daughter '    def call_father(self):        print 'daddy!'son = Son()son.call_father()son.print_name()daughter = Daughter()daughter.call_father()daughter.print_name()print isinstance(son,Father)print isinstance(daughter,Father)'擷取對象資訊'#type()判斷物件類型print type('123')print type(123)print type(son)print type([1,2,3])print type((1,2))print type({1:2,2:3,3:4})print type(set([1,2,3]))#type模組import typesprint type('123') == types.StringTypeprint type(123)==types.IntTypeprint type(u'123')==types.UnicodeTypeprint type([]) == types.ListTypeprint type(str)==types.TypeTypeprint type(int)==type(str)==types.TypeType#isinstance()#之前用過,不做複述print isinstance('a',(str,unicode))#basestring是str和unicode的父類print isinstance('ad',basestring)'擷取對象的所有屬性和方法'#dirprint dir(list)#操作屬性:hasattr,setattr,geattrprint hasattr(lisa,'name')print lisa.namesetattr(lisa,'name','xiaohui')print getattr(lisa,'name')print getattr(lisa,'names',404)print hasattr(lisa,'score')#操作方法print hasattr(lisa,'print_score')f = getattr(lisa,'print_score')f()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.