zoukankan      html  css  js  c++  java
  • python面向对象-4类的继承与方法的重载

     1.类的继承与方法的重载

    上面就是先定义了一个类A,然后由定义了一个类B,B继承了类A,这样B就有了A的非私有属性和方法。

     1 class Washer:
     2     company='ZBL'
     3     def __init__(self,water=10,scour=2):
     4         self._water=water #不想让用户直接访问实例变量,可以标志成私有
     5         self.scour=scour
     6         self.year=2000#这是生产日期
     7         #属性包装,将water属性包装成方法,用户使用water时实际是访问的方法
     8     @staticmethod #定义一个静态方法
     9     def spins_ml(spins):
    10         return spins*0.4
    11         print('company:',Washer.company)
    12         #print('year:',self.year)#错误,静态方法不能使用实例属性
    13     @classmethod
    14     def get_washer(cls,water,scour):#cls相当于实例方法中的self,调用是不用提供这个参数
    15         return cls(water,cls.spins_ml(scour))#cls代表类名Washer,故不是硬编码(改类名是不用改cls,若cls用类名代替也对,但若改类名这个地方也需要改动)
    16     
    17     @property
    18     def water1(self):#如果用户使用 实例.water相当于访问这个方法,而不是真的访问属性
    19         return self._water
    20     
    21     @water1.setter
    22     def water1(self,water):
    23         if 0<water<=500:
    24             self._water=water
    25         else:
    26             print('set Failure!')
    27     @property
    28     def total_year(self):
    29         return 2017-self.year
    30     
    31     def set_water(self,water):
    32         self.water=water        
    33 
    34     def set_scour(self,scour):
    35         self.scour=scour        
    36 
    37     def add_water(self):
    38         print('Add water:',self._water)
    39 
    40     def add_scour(self):
    41         print('Add scour:',self.scour)
    42 
    43     def start_wash(self):
    44         self.add_water()
    45         self.add_scour()
    46         print('Start wash...')
    47         
    48 class WasherDry(Washer):# 建立一个新类,继承自Washer
    49     def dry(self):#新类中可以定义只属于子类的新方法
    50         print('Dry cloths...')
    51     def start_wash(self):#在子类中新定义与父类同名的方法就是方法的重载
    52         self.add_scour()
    53         self.add_water()
    54         
    55 if __name__=='__main__':
    56 ##    print(Washer.spins_ml (8))
    57 ##    w=Washer()
    58 ##    print(w.spins_ml(8))
    59 ##    w=Washer(200,Washer.spins_ml(8))
    60 ##    w.start_wash()
    61     w=WasherDry()
    62     w.start_wash()
    63     print(w.scour,w.company)
    64     w.dry()
  • 相关阅读:
    Elasticsearch:使用function_score及soft_score定制搜索结果的分数
    Elasticsearch:Elasticsearch中的refresh和flush操作指南
    Elasticsearch:top_hits aggregation
    Linux 容器的使用
    编译Linux内核
    GIT的使用
    Linux 小知识翻译
    Linux 小知识翻译
    Linux 小知识翻译
    Linux 小知识翻译
  • 原文地址:https://www.cnblogs.com/zhubinglong/p/6953238.html
Copyright © 2011-2022 走看看