fromtypingimportUnionfromdataclassesimportdataclassimportpymysql.cursorsconnection=pymysql.connect(host='localhost',user='root',password='',db='test',charset='utf8mb4')@dataclassclassSubject:id:intcat_id:inttitle:strkind:int=0@classmethoddefget(cls,id:int)->Union[Subject,None]:withconnection.cursor()ascursor:cursor.execute("select id, cat_id, title, kind from subject where id=%s",id)rs=cursor.fetchone()ifnotrs:returnNonereturncls(*rs)defset_cover(self,cover:ImageCover):...@dataclassclassImageCover:id:intidentifier:str
In [1]: from movie.models.base import Subject
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-b027a5ff7e8f> in <module>
----> 1 from a import Subject
~/workspace/movie/movie/models/base.py in <module>
12
13
---> 14 @dataclass
15 class Subject:
16 id: int
~/workspace/movie/movie/models/base.py in Subject()
20
21 @classmethod
---> 22 def get(cls, id: int) -> Union[Subject, None]:
23 with connection.cursor() as cursor:
24 cursor.execute(
NameError: name 'Subject' is not defined
一周后的 21 日,又拍了一次 B 超和 CT,这次 B 超没找到结石,其中一个原因是腹部有气看不清楚,但是依然有肾积水,做 B 超的医生说应该结石还在,我不开心了😒,之后的 CT 也证实了这一点。但好消息是结石比之前小了一些,不到 3 毫米,而且已经到了输尿管和膀胱连接处,这里是最后一处输尿管狭窄的部分,另外主治医生说结石颜色变浅了一些,可能碎的比较薄了一些。
# lib.pyimportwarningswarnings.filterwarnings('default')# Python 3.2开始默认会隐藏DeprecationWarningdefnew_function(arg,other):print('plz use me!')_deprecated_map={'old_function':new_function}def__getattr__(name):ifnamein_deprecated_map:switch_to=_deprecated_map[name]warnings.warn(f'{name} is deprecated. Switch to {__name__}.{switch_to.__name__}.',DeprecationWarning)returnswitch_toraiseAttributeError(f"module {__name__} has no attribute {name}")
def __dir__():
return __all__ + ('__author__', '__doc__')
def __getattr__(name):
global ProcessPoolExecutor, ThreadPoolExecutor
if name == 'ProcessPoolExecutor':
from .process import ProcessPoolExecutor as pe
ProcessPoolExecutor = pe
return pe
if name == 'ThreadPoolExecutor':
from .thread import ThreadPoolExecutor as te
ThreadPoolExecutor = te
return te
raise AttributeError(f"module {__name__} has no attribute {name}")
>>> @attr.s
... class C(object):
... x = attr.ib()
... @x.validator
... def check(self, attribute, value):
... if value > 42:
... raise ValueError("x must be smaller or equal to 42")
>>> C(42)
C(x=42)
>>> C(43)
Traceback (most recent call last):
...
ValueError: x must be smaller or equal to 42
属性参数:
>>> def x_smaller_than_y(instance, attribute, value):
... if value >= instance.y:
... raise ValueError("'x' has to be smaller than 'y'!")
>>> @attr.s
... class C(object):
... x = attr.ib(validator=[attr.validators.instance_of(int),
... x_smaller_than_y])
... y = attr.ib()
>>> C(x=3, y=4)
C(x=3, y=4)
>>> C(x=4, y=3)
Traceback (most recent call last):
...
ValueError: 'x' has to be smaller than 'y'!
属性类型转化
Python 不会检查传入的值的类型,类型错误很容易发生,attrs 支持自动的类型转化:
>>> @attr.s
... class C(object):
... x = attr.ib(converter=int)
>>> o = C("1")
>>> o.x
1
In:frompathlibimportPathIn:Path.home()Out:PosixPath('/Users/dongweiming')# 用户目录In:path=Path('/user')In:path/'local'# 非常直观Out:PosixPath('/user/local')In:str(path/'local'/'bin')Out:'/user/local/bin'In:f=Path('example.txt')In:f.write_bytes('This is the content'.encode('utf-8'))Out[16]:19In:withf.open('r',encoding='utf-8')ashandle:# open现在是方法了....:print('read from open(): {!r}'.format(handle.read()))....:readfromopen():'This is the content'In:p=Path('touched')In:p.exists()# 集成了多个常用方法Out:FalseIn:p.touch()In:p.exists()Out:TrueIn:p.with_suffix('.jpg')Out:PosixPath('touched.jpg')In:p.is_dir()Out:FalseIn:p.joinpath('a','b')Out:PosixPath('touched/a/b')
In:name='Fred'In:f'My name is {name}'Out:'My name is Fred'In:fromdatetimeimport*In:date=datetime.now().date()In:f'{date} was on a {date:%A}'Out:'2018-01-17 was on a Wednesday'In:deffoo():....:return20....:In:f'result={foo()}'Out:'result=20'
@magic_arguments.magic_arguments()# 最上面@magic_arguments.argument('--breakpoint','-b',metavar='FILE:LINE',help=""" Set break point at LINE in FILE. """)# 这种argument可以有多个@magic_arguments.argument('statement',nargs='*',help=""" Code to run in debugger. You can omit this in cell magic mode. """)@line_cell_magicdefdebug(self,line='',cell=None):args=magic_arguments.parse_argstring(self.debug,line)# 要保持第一个参数等于这个方法名字,这里就是self.debug...
classCounter(dict):...def__missing__(self,key):'The count of elements not in the Counter is zero.'# Needed so that self[missing_item] does not raise KeyErrorreturn0