Python 魔法方法 单例模式 定制属性 @装饰器 内置装饰器 @property @staticmethod @classmethod

__new__方法, 第一个执行, 然后执行__init__方法

class Foo:
    def __new__(cls, *args, **kwargs):
        print('__new__')
        return super().__new__(cls)

    def __init__(self):
        print('__init__')


foo = Foo()
print(foo)		# __new__  __init__

非单例模式, 每次创建都是新对象

fee = Foo()
print(id(fee))
print(id(foo))

单例模式 只创建一个对象

class SimpleFoo:
    _instance = None  # 代表实例

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, name):
        self.name = name


a = SimpleFoo('小米')
b = SimpleFoo('华为')
print(id(a))
print(id(b))  		# a和b是同一个对象
print(a is b)  		# True
print(a.name)  		# 华为
print(b.name)  		# b的属性覆盖了a的属性

定制属性

class Person:
    def __init__(self, name):
        self.name = name


p = Person('张三')

hasattr 判断属性是否存在

print(hasattr(p, 'name'))

getattr 获取属性

print(getattr(p, 'name'))

setattr 设置属性, 有则改, 无则加

setattr(p, 'age', 18)
print(getattr(p, 'age'))

delattr 删除属性

delattr(p, 'age')
print(getattr(p, 'age', '不存在'))

@函数装饰器, 不改变原函数调用的基础上添加功能

def foo(func):
    def wrapper():
        print('装饰器')
        func()

    return wrapper


@foo
def bar():
    print('bar')


bar()  # 装饰器 bar

内置装饰器 @property(像访问属性一样调用方法) @staticmethod(静态方法, 不用实例化, 类名.方法名()调用) @classmethod(传递类本身)

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

    @staticmethod
    def is_square(width, height):
        return width == height

    @classmethod
    def new_square(cls, side):
        return cls(side, side)


rect = Rectangle(10, 20)
print(rect.area)  						# 200
print(Rectangle.is_square(10, 20))  	# False
print(Rectangle.new_square(10))  		# <__main__.Rectangle object at 0x0000020D8B0B0B80>
print(Rectangle.new_square(10).area)  	# 100


import time
def run_time(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print('{}运行时间: {}'.format(func.__name__, end - start))
    return wrapper


@run_time
def type_method():
    for i in range(10000000):
        type("hello world")
        
        
@run_time
def isinstance_method():
    for i in range(10000000):
        isinstance("hello world", str)


type_method()
isinstance_method()      # isinstance_method要快一点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值