django restframework 知识准备

作者: ropon 分类: Django 发布时间: 2019-01-11 13:23
from django.test import TestCase
from django.utils.decorators import classonlymethod


# classmethod classonlymethod
class Ropon(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 定义类方法
    @classmethod
    def sleepping(cls):
        print("Ropon is sleepping!")

    # 定义类方法 配置仅允许类调用
    @classonlymethod
    def shopping(cls):
        print("Ropon is shopping!")

    def eatting(self):
        print(self.name, "is eatting!")

ropon = Ropon("ropon", 18)
# ropon.sleepping()
# Ropon.sleepping()

# ropon.shopping() # 报错
# Ropon.shopping()

# 打印实例化对象所有属性不含方法
# print(ropon.__dict__)

# 打印类所有属性及方法
# print(Ropon.__dict__)

# hasattr getattr setattr
class Pengge(Ropon):
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def singging(self):
        print(self.name, "is singging!")

    def show_self(self):
        print(self)

class LuoPeng(Pengge):
    pass

pengge = Pengge("pengge", 19, "male")
lp = LuoPeng("luopeng", 20, "male")


# 判断类或实例化对象中是否有对应属性
# print(hasattr(pengge, "name"))
# print(hasattr(pengge, "age"))
# print(hasattr(pengge, "gender"))
# print(hasattr(Ropon, "sleepping"))

# 取类或实例化对象中是否有对应属性
# ret = getattr(lp, "singging")
# ret()

# ret2 = getattr(Ropon, "sleepping")
# ret2()

# 向类或实例化对象中添加属性及值
# setattr(lp, "fav", ["lanqiu", "pingpong"])
# setattr(LuoPeng, "fav2", ["lanqiu2", "pingpong2"])
# print(LuoPeng.__dict__)
# print(lp.fav)
# print(LuoPeng.fav2)

# self 指向
# 谁调用指向谁
# pengge.show_self()
# lp.show_self()

# json序列化及反序列化
person = {
    'name': 'ropon',
    'age': 18
}

# import json
# 序列化
# json_data = json.dumps(person)
# print(json_data)

# 反序列化
# res = json.loads(json_data)
# print(res)

# JavaScript 序列化
# json_data = JSON.stringify(person)

# JavaScript 反序列化
# res = JSON.parse(json_data)

def outer(func):
    def inner(*args, **kwargs):
        import time
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print(end_time - start_time)
    return inner

# 加装饰器 返回函数执行时间
@outer
def add(x, y):
    return x + y

# add(1, 2)

# 基于类扩展功能
class Father(object):
    def show(self):
        print("Father show is excuted")

class Son(Father):
    def show(self):
        print("Son show is excuted")
        super().show()

father = Son()
father.show()

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!