__new__方法, 第一个执行, 然后执行__init__方法
class Foo:
def __new__(cls, *args, **kwargs):
print('__new__')
return super().__new__(cls)
def __init__(self):
print('__init__')
foo = Foo()
print(foo)
非单例模式, 每次创建都是新对象
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))
print(a is b)
print(a.name)
print(b.name)
定制属性
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()
内置装饰器 @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)
print(Rectangle.is_square(10, 20))
print(Rectangle.new_square(10))
print(Rectangle.new_square(10).area)
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()