1、staticmethod装饰器
2、deftest_iter():
3、使用三对双引号"""或者三对单引号'''包围起来的文本可以作为多行注释。这种方式通常用于函数或类的文档字符串(string)注释,用于提供关于函数或类的说明和文档。
4、print"runningafterException"
5、help='Showthishelpmessageandexit.')
6、executingstatic_foo(para)
7、frombaseimportAPIBase
8、property有三个方法getter(),setter()和delete()来指定fget,fset和fdel。这表示以下这行
9、defstatic_foo(x):
10、deftest_second():
11、classStudent(object):
12、#可以在这里写入详细的说明和文档
13、python中#是Python的单行注释符号(#)
14、__init__method
15、ExitedwithException
16、defread(self):
17、deftest_with():
18、Exception
19、printfilter(lambdax:x%2!=0,lst)
20、printline
21、defsingleton(cls):
22、#python内建函数
23、使用装饰器实现简单的单例模式
24、def__enter__(self):
25、defmain(argv=None):
26、fun=partial(sum,2)#事先绑定一个参数,fun成为一个只需要一个参数的可调用变量
27、ExitedwithoutException
28、('xiaoming','china','10'),
29、"para":5,
30、raiseValueError('scoremustbetween0~100!')
31、return','.join(map(str,self.lst))
32、print"executingfoo(%s,%s)"%(self,x)
33、property装饰器
34、raiseValueError('scoremustbeaninteger!')
35、classmethod装饰器,类方法(给人感觉非常类似于OC中的类方法),其中第一个隐式参数为类
36、returnTrue
37、```python
38、一行作判断
39、>>>name="andrew"
40、普通成员函数,其中第一个隐式参数为对象
41、print"__enter__method"
42、print"AttributeError!"
43、writer=csv.writer(f)
44、神奇partial
45、deftest_exec():
46、test_three_method()
47、return0#success
48、#例如,这里可以介绍函数的参数和返回值等信息
49、#两者具有相同的地址
50、#普通成员函数
51、with语句需要支持上下文管理协议的对象,上下文管理协议包含__enter__和__exit__两个方法.with语句建立运行时上下文需要通过这两个方法执行进入和退出操作.
52、看一下下面这个例子
53、'"%s"ignored.'%(args,))
54、runningmy_with
55、def__iter__(self):
56、parser.error('programtakesnocommand-linearguments;'
57、new_lst=lst[0]iflstisnotNoneelseNone
58、test_partial()
59、importcsv
60、iter魔法
61、exec和eval在执行代码时,除了返回值其他行为都相同
62、"test_second":test_second
63、[1,3,5]
64、井号(#)常被用作单行注释符号,在代码中使用#时,它右边的任何数据都会被忽略,当做是注释。
65、exec(compile(__file__f.read(),__file__,"exec"))
66、parser.add_option(#customizeddescription;put--helplast
67、ifargs:
68、obj.static_foo("para")#静态方法并没有任何隐式参数,但是要通过对象或者类进行调用
69、'export','info','interface','stream']
70、returnwrer
71、args=list(part_args)
72、withopen('data.csv','rb')asf:
73、ifexc_tracebackisNone:
74、returnsettings,args
75、writer.writerows(data)#多行写入
76、将鼠标放到要执行的代码行,按电脑键盘的F8
77、classMyWith(object):
78、deftest_third():
79、staticmethod装饰器,没有任何隐式参数.python中的静态方法类似与C++中的静态方法
80、#函数输出
81、defpartial(func,*part_args):
82、defclass_foo(cls,x):
83、instances[cls]=cls(*args,**kwargs)
84、------分割线-----
85、if__name__=='__main__':
86、enable_logging_to_kids,info)
87、returnself._score
88、obj=A()
89、instances=dict()#初始为空
90、#输出结果
91、在JupyterNotebook中,可以使用Shift+Enter来运行当前行。具体的快捷键可能会因IDE或环境的不同而有所变化,建议查阅相关文档或设置以获取准确的信息。
92、classA(object):
93、property(fget=None,fset=None,fdel=None,=None)
94、将property与装饰器结合实现属性私有化(更简单安全的实现get和set方法)
95、action={#可以看做是一个sandbox
96、reader=csv.reader(f)
97、executingclass_foo(
98、Traceback(mostrecentcalllast):
99、printnew_lst
100、def_singleton(*args,**kwargs):
101、printgetattr(my_test,"test")
102、利用用闭包的特性绑定预先绑定一些函数参数,返回一个可调用的变量,直到真正的调用执行
103、runningbeforeException
104、thenamedattributeofobject.namemustbeastring.Ifthestringis
105、执行结果如下:
106、#从csv中读取文件,基本和传统文件读取类似
107、'Storage','disable_logging_to_stderr','enable_logging_to_kids',
108、神秘eval
109、@score.setter#相当于score=property.setter(score)
110、deftest_getattr():
111、test_with()
112、exec
113、obj=TestIter()
114、print"MethodError!"
115、print"testmethod"
116、deftest_three_method():
117、fromdecoratorimportinterface,export,stream
118、print"executingclass_foo(%s,%s)"%(cls,x)
119、settings,args=process_command_line(argv)
120、print"hello"
121、#run(settings,args)
122、A.class_foo("para")#更直接的类方法调用
123、exceptAttributeError:
124、@singleton
125、self._score=value
126、test_getattr()
127、print"executingstatic_foo(%s)"%x
128、知道具体原理,我们可以自定义支持上下文管理协议的类,类中实现__enter__和__exit__方法
129、在Python中,可以使用以下三种方式来编写多行注释:
130、provided,otherwiseAttributeErrorisraised.
131、fromstorageimportStorage
132、obj.class_foo("para")#此处类作为隐式参数被传入,就是cls
133、returnself.read()
134、forrowinreader:
135、#!/usr/bin/envpython
136、returnFalse
137、defwrer(*extra_args):
138、printfun(3)#实现执行的即是sum(2,3)
139、print"second"
140、'-h','--help',action='help',
141、在stackoverflow给出了类似与partial的运行方式
142、defscore(self,value):
143、fromserverimportServer
144、详细原理可以查看这篇文章,浅谈Python的with语句
145、在传入字符串时,会使用compile(source,'
146、lst=[1,2,3,4,5,6]
147、getattr(my_test,"say")()
148、"test_second":test_second,
149、@staticmethod#使用staticmethod进行装饰
150、这是一个多行注释的示例。
151、defsum(a,b):
152、ifclsnotininstances:#如果不存在,则创建并放入字典
153、testattribute
154、File"test_with.py",line33,in
155、命令行处理
156、其中上下文表达式是跟在with之后的表达式,该表示大返回一个上下文管理对象
157、testmethod
158、通过__str__的重写,可以直接通过想要的形式打印对象
159、returnfunc(*args)
160、test_exec()#无法看到执行结果
161、@property#相当于property.getter(score)或者property(score)
162、#常见with使用场景
163、classTestIter(object):
164、obj.foo("para")#此处obj对象作为成员函数的隐式参数,就是self
165、"test_first":test_first,
166、sys.exit(status)
167、当发布python第三方package时,并不希望代码中所有的函数或者class可以被外部import,在__init__.py中添加__all__属性,
168、ifargvisNone:
169、raiseException
170、ifvalue100:
171、各种时间形式转换
172、__all__=['APIBase','Client','LogFormatter','Server',
173、return3
174、deffoo(self,x):
175、returna+b
176、通过yield和__iter__的结合,我们可以把一个对象变成可迭代的
177、deftest_partial():
178、if__name__=='_
179、getattr
180、print"runningmy_with"
181、#furtherprocesssettings&argsifnecessary
182、读写csv文件
183、另一种方式是使用多个单行注释来实现多行注释的效果。
184、只发一张网上的,然后差文档就好了,这个是记不住的
185、printres
186、classTest(object):
187、printrow
188、exceptAttributeError:#没有该属性,且没有指定返回值的情况下
189、my_test=TestGetAttr()
190、writer.writerow(['name','address','age'])#单行写入
191、test_iter()
192、@classmethod#使用classmethod进行装饰
193、#执行结果
194、withMyWith()asmy_with:
195、ifnotisinstance(value,int):
196、print"third"
197、foreleinxrange(len(self.lst)):
198、print"__exit__method"
199、formatter=optparse.TitledHelpFormatter(width=78),
200、argv=sys.argv[1:]
201、defscore(self):
202、A.static_foo("para")
203、可以使用#符号在每行的开头添加单行注释,通过连续使用多行注释符号可以创建多行注释效果。
204、printobj
205、无论使用哪种方式,多行注释都不会被解释器执行,因此不会对程序的运行产生任何影响。它们主要用于提高代码可读性和维护性,帮助其他开发人员理解代码的用途和功能。
206、t2=Test()
207、print"------分割线-----"
208、"test_third":test_third
209、print"__init__method"
210、deftest_first():
211、字符串格式化
212、#所有奇数都会返回True,偶数会返回False被过滤掉
213、#打印结果
214、test_first()
215、`argv`isalistofarguments,or`None`for``sys.argv[1:]``.
216、fget是获取属性的值的函数,fset是设置属性值的函数,fdel是删除属性的函数,是一个字符串(likeacomment).从实现来看,这些参数都是可选的
217、证明了会先执行__enter__方法,然后调用with内的逻辑,最后执行__exit__做退出处理,并且,即使出现异常也能正常退出
218、settings,args=parser.parse_args(argv)
219、#-*-coding:utf-8-*-
220、withopen('data.csv','wb')asf:
221、fromfunctoolsimportpartial
222、action={
223、thenameofoneoftheobject’sattributes,theresultisthevalueof
224、fornuminobj:
225、getattr(object,name[,default])Returnthevalueof
226、returnnum
227、exec"test_second"inaction
228、#checknumberofarguments,verifyvalues,etc.:
229、data=[
230、#单例装饰器
231、类中两种常用的装饰,首先区分一下他们
232、printt1,t2
233、__repr__=__str__
234、通过string类型的name,返回对象的name属性(方法)对应的值,如果属性不存在,则返回默认值,相当于object.name
235、#向csv文件写入
236、#defineoptionshere:
237、('Lily','USA','12')]
238、deftest_eavl():
239、self.lst=[1,2,3,4,5]
240、Returna2-tuple:(settingsobject,argslist).
241、#使用范例
242、#licationcodehere,like:
243、print"ExitedwithoutException"
244、defprocess_command_line(argv):
245、print"runningbeforeException"
246、else:
247、#initializetheparserobject:
248、yieldele
249、with的魔力
250、deftest_second(num):
251、return_singleton
252、parser=optparse.OptionParser(
253、status=main()
254、returninstances[cls]
255、t1=Test()
256、def__str__(self):
257、condition="para==5andtest_second(test_first)>5"
258、executingfoo(
259、#直接调用噗通的成员方法
260、exec在Python中会忽略返回值,总是返回None,eval会返回执行代码或语句的返回值
261、装饰器之单例
262、>>>"mynameis{name}".format(name=name)
263、一个非常好用,很多人又不知道的功能
264、returnself#返回对象给as后的变量
265、args.extend(extra_args)
266、res=eval(condition,action)#解释condition并根据action对应的动作执行
267、defsay(self):
268、在Python中,可以使用IDE(集成开发环境)进行代码调试,通常这些环境都提供了单行运行代码的快捷键。例如,在PyCharm中,可以使用快捷键Shift+F9来运行当前行。
269、add_help_option=None)
270、eval我理解为一种内嵌的python解释器(这种解释可能会有偏差),会解释字符串为对应的代码并执行,并且将执行结果返回
271、printnum
272、__exit__method
273、filter的用法
274、可以在这里写入详细的说明和文档。
275、partial使用上很像C++中仿函数(函数对象).
276、当条件满足时,返回的为等号后面的变量,否则返回else后语句
277、lst=[1,2,3]
278、#这是一个多行注释的示例
279、thatattribute.Forexample,getattr(x,‘foobar’)isequivalentto
280、例如,这里可以介绍函数的参数和返回值等信息。
281、定义私有类属性
282、x.foobar.Ifthenamedattributedoesnotexist,defaultisreturnedif
283、forlineinmy_file:
284、def__init__(self):
285、def__exit__(self,exc_type,exc_value,exc_traceback):
286、File"bin/python",line34,in
287、pass
288、print"ExitedwithException"
289、Python奇技淫巧
290、fromclientimportClient
291、fromutilimport(LogFormatter,disable_logging_to_stderr,
292、相对filter而言,map和reduce使用的会更频繁一些,filter正如其名字,按照某种规则过滤掉一些元素
293、withopen("test.","r")asmy_file:#注意,是__enter__()方法的返回值赋值给了my_file,
294、classTestGetAttr(object):
295、test="testattribute"
296、try:
297、__enter__method
298、该list中填写可以import的类或者函数名,可以起到限制的import的作用,防止外部import其他函数或者类
299、File"test_with.py",line28,intest_with
300、'mynameisandrew'