zoukankan      html  css  js  c++  java
  • 面向对象之封装与静态属性

     1 class Shop:
     2     dz=0.5  #对商品降价打折处理
     3     def __init__(self,name,price):
     4         self.name=name
     5         self.__price=price  #私有化类的属性外部不可直接被调用
     6     @property
     7     def price(self):
     8         return self.__price*Shop.dz
     9     @price.setter
    10     def price(self,new_price):         #重新设置私有属性的值
    11         self.__price=new_price
    12 s1=Shop('apple',5)
    13 print(s1.price)
    14 s1.price=10
    15 print(s1.price)

    父类的私有属性子类也是无法通过继承来调用的。

    原生Python本身没有接口类的概念

    接口类和抽象类都不能实例化

    接口类支持多继承 但父类的具体方法必须不被实现 pass 起到约束作用

    抽象类不支持多继承,具体方法可以实现一部分

    Python天生支持多态

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    类方法classmethod和静态方法staticmethod 都是类调用的

    当然对象也可以调用 但是推荐类去调用

    类方法有一个默认参数cls 代表这个类

    静态方法没有默认参数 和普通函数差不多

     1 class Login:
     2     __num=2
     3     def __init__(self,name,pasd):
     4         self.name=name
     5         self.pasd=pasd
     6     @staticmethod
     7     def get_use_psd():
     8         user=input('请输入用户名')
     9         pasd=input('请输入密码')
    10         Login(user,pasd)
    11     @classmethod
    12     def change_num(cls,new_num):
    13         cls.__num=new_num
    14     @staticmethod
    15     def get_num():
    16         print(Login.__num)
    17 # Login.get_use_psd()
    18 Login.change_num(5)
    19 print(Login.get_num())

    类方法和静态方法的使用

  • 相关阅读:
    怎么查看京东店铺的品牌ID
    PPT编辑的时候很卡,放映的时候不卡,咋回事?
    codevs 1702素数判定2
    codevs 2530大质数
    codevs 1488GangGang的烦恼
    codevs 2851 菜菜买气球
    hdu 5653 Bomber Man wants to bomb an Array
    poj 3661 Running
    poj 1651 Multiplication Puzzle
    hdu 2476 String Painter
  • 原文地址:https://www.cnblogs.com/wen-kang/p/9378491.html
Copyright © 2011-2022 走看看