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()
 
原文地址:https://www.cnblogs.com/changwoo/p/9601868.html