5个内置方法 property、classmethod、staticmethod、isinstance、issubclass

#!/usr/bin/env/python
#-*- coding:utf-8 -*-
#author: zhangliang
class Goods:
    __discount = 0.8
    def __init__(self, price):
        self.__price = price

    @property
    def price(self):
        return self.__price * Goods.__discount
    # 类方法:当我们写了一个类中的方法,发现并没有使用到对象的任何属性,只是用到了类的命名空间中的变量
    # 你就将这个方法定义为一个被@classmethod装饰器装饰的方法,这个方法就被称为类方法。
    @classmethod
    def change_discount(cls, new):
        cls.__discount = new
    # 本质上就一个函数,不需要默认的类,self对象等参数;
    @staticmethod
    def look():
        print("静态方法")

g = Goods(30)
print(g.price)
Goods.change_discount(60)
print(g.price)
Goods.look()

"""
property classmethod staticmethod 都是修饰方法的
@property 是把一个普通的方法装饰成属性
@classmethod 是把一个普通方法装饰成类方法
    #调用方式 类名.方法名
    #定义方式 参数 从self-->cls
@staticmethod 是把一个普通的方法装饰成类中的函数/静态方法
    #调用方式 类名.方法名
    #定义方式 参数 从self-->没有默认必须传的参数了
"""
# instance的用法
print(isinstance(g, Goods))

#issubclass
class Good(Goods):
    pass
print(issubclass(Good, Goods))

  

posted on 2018-09-27 21:03  zl666张良  阅读(93)  评论(0)    收藏  举报