装饰器、修饰符

装饰器 import time def counttime(func): def test(*args): start_time=time.time() end_time=time.time() func(*args) total_time=end_time-start_time print("total:{0:.2}s".format(total_time)) return test @counttime def printer(s): for i in range(10000):print(s) print("start") printer("hello") @classmethod 无需实例化即可调用,实例不可用 class C(object): @classmethod def f(): print('hello'); C.f() @staticmethod 无需实例化即可调用,实例化后仍然可用 class C(object): @staticmethod def f(): print('hello'); C.f() c=C() c.f()

March 17, 2022 · 1 min · 编程笔记本

抽象类

抽象类不可实例化,被abstractclassmethod修饰的函数必须重写 from abc import ABCMeta,abstractclassmethod class A(metaclass=ABCMeta): def __init__(self): pass @abstractclassmethod def say(self,s): pass class B(A): def __init__(self): pass def say(self,s): print(s) b=B() b.say("hello") output: hello

March 17, 2022 · 1 min · 编程笔记本

property与setter:属性管理

class people(): def __init__(self,name): self.__name=name @property def name(self): return self.__name @name.setter def name(self,name): if not isinstance(name,str): raise TypeError('expected a string') self.__name=name me=people("john") print(me.name) me.name="tony" print(me.name) output: john tony

March 16, 2022 · 1 min · 编程笔记本

Python上下文管理

class people(): def __init__(self,name): self.__name=name def __enter__(self): print('enter') def __exit__(self,exc_ty, exc_val, tb): print('exit') def say(self,s): print(s) me=people("john") with me: me.say('hello') output: enter hello exit

March 16, 2022 · 1 min · 编程笔记本

缩短你的垃圾🐔代码

L = [] n = 1 while n <= 99: L.append(n) n = n + 2 可用下面多种方法实现缩短: [i for i in range(1,100,2)] list(range(1, 100, 2)) list(range(1, 100))[::2] list(range(1, 100)[::2]) list(range(100))[1::2] [2*x-1 for x in range(1,51)]

March 16, 2022 · 1 min · 编程笔记本