Class

  • 私有方法
  • __del__方法
  • 繼承;多繼承
  • 重寫;
  • 多態;
  • 類屬性;實例屬性;
  • 類方法;實例方法;靜態方法;
  • __new__方法
  • 建立單例對象
  • 異常
  • 模塊自我測試和調用相沖突的解決辦法
  • 設計4s店類(pass)
 
私有方法:
class Dog:
   #私有方法
   def __send_msg(self):
      print('------正在發送短信------')
   def send_msg(self,money):
      if money > 10000:
         self.__send_msg()
      else:
         print('-----您的餘額不足,請充值-----')
 
dog = Dog()
dog.send_msg(5000)
__del__方法:
class Dog:
   def __del__(self):
      print('-----英雄over-----')
dog1 = Dog()
dog2 = dog1
 
del dog1 #此時不會調用__del__方法,由於這個對象還有其餘變量指向它,即引用計算不是0
del dog2 #此時會調用__del__方法,由於已經沒有變量指向它了
print('=================')
#若是在程序結束時,有些對象還存在,那麼python解釋器會自動調用它們的__del__方法來完成清理工做
inherit:
#INHERIT_ONE
class Anaimal:
    def eat(self):
        print('-----eat-----')
    def drink(self):
        print('-----drink-----')
    def play(self):
        print('-----play-----')
    def run(self):
        print('-----run-----')
class Dog(Anaimal):
    def bark(self):
        print('-----bark-----')
class Cat(Anaimal):
    def catch(self):
        print('-----catch-----')
 
tom = Cat()
tom.eat()
tom.catch()
#if used tom.bark, you will get a error.
#INHERIT_TWO
class Anaimal:
    def eat(self):
        print('-----eat-----')
    def drink(self):
        print('-----drink-----')
    def play(self):
        print('-----play-----')
    def run(self):
        print('-----run-----')
class Cat(Anaimal):
    def catch(self):
        print('-----catch-----')
class Animation_Cat(Cat):
    def speak(self):
        print('-----speak-----')
 
tom = Animation_Cat()
tom.eat()
tom.catch()
tom.speak()
#Tom can use Anaimal, Cat and Animation_Cat.  
#INHERIT_ISSUE
class Anaimal:
     def __init__(self):
        self.num = 'I can inherit!'
        self.__num = 1 #私有屬性
    def __swim(self): #私有方法
        print('-----swim-----')
    def run(self):
        self.__swim() #公有方法下的私有屬性
        print(self.__num) #公有方法下的私有方法
class Cat(Anaimal):
    #Attention:若是是這裏的 公有方法下的私有屬性或方法會報錯,緣由能夠走一遍循環:先找本身的方法,找不到的話,若是是公有方法往父類上找,私有方法由於不能被繼承,直接報錯。
    pass
 
tom = Cat()
#tom.__swim() #AttributeError:私有method can't be inherit!
#print(tom.__num) #AttributeError:私有屬性 can't be inherit!
print(tom.num)
tom.run() #包含在共有屬性中的私有方法和私有屬性能夠被繼承!
 
#Conclusion:通常來講,公有屬性和公有方法會被繼承,而私有屬性和私有方法卻不會被繼承。可是存在兩種特殊狀況:若是是父類的公有方法下調用私有屬性和私有方法會被繼承。若是是子類的公有方法下調用私有屬性和私有方法會報錯
#Conclusion:The general rule is that common attributes and common methods are inherited, private attributes and private methods are not inherited. But there are two kinds of special cases: ① If it is public methods of the parent with private property and private methods will be inherited. ② If it is public methods of the son with private property and private methods will not be inherited.
#Multiple inheritance(多繼承)
class base(object):
    def test(self):
        print('-----test-----')
class A(base):
    def test1(self):
        print('-----test1-----')
class B(base):
    def test2(self):
        print('-----test2-----')
class C(A,B):
    pass
 
tom = C()
tom.test()
tom.test1()
tom.test2()
 
#多繼承的注意點:print(tom.__mro__)
#會打印調用一個方法時搜索的順序(C3算法)
#儘可能避免在類中出現相同的方法
REWRITE:
#REWRITE_ONE
class Anaimal:
    def eat(self):
        print('-----eat-----')
    def drink(self):
        print('-----drink-----')
    def play(self):
        print('-----play-----')
    def run(self):
        print('-----run-----')
class Cat(Anaimal):
    def catch(self):
        print('-----catch-----')
class Animation_Cat(Cat):
    def speak(self):
        print('-----speak-----')
     def catch(self):
        #if you rewrite 'catch', his father will be cover.
        print('-----not catch-----')
    
tom = Animation_Cat()
tom.eat()
tom.catch()
tom.speak()
#REWRITE_TWO
class Anaimal:
    def eat(self):
        print('-----eat-----')
    def drink(self):
        print('-----drink-----')
    def play(self):
        print('-----play-----')
    def run(self):
        print('-----run-----')
class Cat(Anaimal):
    def catch(self):
        print('-----catch-----')
class Animation_Cat(Cat):
    def speak(self):
        print('-----speak-----')
    def catch(self):
        print('-----not catch-----')
          #if you want to call son's catch first, then call father's catch.
        #the first method
        Cat.catch(self)
        #the second method
        super().catch()
 
tom = Animation_Cat()
tom.catch()
polymorphism(多態):
class Dog(object):
    def introduce(self):
        print('你們好,我是xxx')
class Xiaotq(Dog):
    def introduce(self):
        print('hello,我是神犬')
def function(temp):
    #只有在運行的時候才肯定屬於誰
    temp.introduce()
 
dog1 = Dog()
dog2 = Xiaotq()
function(dog1)
function(dog2)
類屬性和示例屬性:
class Tool(object):
     #類屬性
    num = 0
    def __init__(self, new_name):
        #實例屬性
        self.name = new_name
        #對類屬性+1
        Tool.num += 1
 
tool1 = Tool('鐵鍬')
tool2 = Tool('工兵鏟')
tool3 = Tool('水桶')
print(Tool.num)
__new__方法:
class Cat(object):
    def __init__(self):
        print('----init方法----')
    def __del__(self):
        print('----del方法----')
    def __str__(self):
        print('----str方法----')
    def __new__(cls):
        print('----new方法----,,,')
        return object.__new__(cls)
 
tom = Cat()
#並無很懂,可是流程是先調用__new__,接收到它的返回值以後,調用__init__方法,而不是從__new__中調用__init__方法
建立單例對象:
class Cat(object):
    __instance = None
    #建立一個私有類屬性
    def __new__(cls):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            #返回上一次建立的對象的引用
            return cls.__instance
 
tom = Cat()
print(id(tom))
cat = Cat()
print(id(cat))
#只初始化一次對象
class Cat(object):
    __instance = None
    #建立一個私有類屬性
    def __new__(cls, name):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            #返回上一次建立的對象的引用
            return cls.__instance
    def __init__(self, name):
        self.name = name
 
tom = Cat('湯姆')
print(id(tom))
print(tom.name)
cat = Cat('小貓')
print(id(cat))
print(cat.name)
#只初始化一次對象2
class Cat(object):
    __instance = None
    __init_flag = False
    #建立一個私有類屬性
    def __new__(cls, name):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            #返回上一次建立的對象的引用
            return cls.__instance
    def __init__(self, name):
        if Cat.__init_flag == False:
            self.name = name
            Cat.__init_flag = True
 
tom = Cat('湯姆')
print(id(tom))
print(tom.name)
cat = Cat('小貓')
print(id(cat))
print(cat.name)
異常:
#異常處理-基本功能
try:
    print(un)
    open('xxx.txt')
except (NameError,FileNotFoundError):
    print('捕獲到異常')
except Exception as result:
    #Exception是全部異常的總稱
    print('捕獲到其餘異常')
    print('result')
else:
    print('沒有異常纔會執行的功能')
finally:
    #不管上面是否出現異常,都會執行finally
    print('-----finally----')
    f.close()
    print('文件關閉')
#異常的傳遞
def test1():
    print(num)
def test2():
    test1()
def test3():
    try:
        test2()
    except Exception as result:
        print('已捕獲到異常,異常信息爲:(%s)'%result)
 
test3()
#拋出自定義異常
class ShortInputException(Exception):
    #自定義的異常類
    def __init__(self, length, atleast):
        #super().__init__()
        self.length = length
        self.atleast = atleast
 
def main():
    try:
        s = input('請輸入字符:')
        if len(s) < 3:
            raise ShortInputException(len(s),3)
    except ShortInputException as result:
        print('ShortInputException:輸入的長度是%d,長度至少是%d'%(result.length,result.atleast))
    else:
        print('noerror')
 
main()
#異常處理中拋出異常
class Test(object):
    def __init__(self, switch):
        self.switch = switch #開關
    def calc(self, a, b):
        try:
            return a/b
        except Exception as result:
            if self.switch:
                print('捕獲開啓,已經捕獲到了異常,信息以下:')
                print(result)
            else:
                #從新拋出這個異常,此時就不會被這個異常處理給捕獲到,從而觸發默認的異常處理
                raise
 
a = Test(True)
a.calc(11,0)
print('---------------分割線--------------------')
a.switch = False
a.calc(11,0)
#模塊自我測試和調用相沖突的解決辦法
def test1():
    print('-----test1-----')
def test2():
    print('-----test2-----')
def main():
        test1()
        test2()
if __name__ == '__main__':
    main()
相關文章
相關標籤/搜索