- N +

property line?Property Lines

大家好,感謝邀請,今天來為大家分享一下property line的問題,以及和Property Lines的一些困惑,大家要是還不太明白的話,也沒有關系,因為接下來將為大家分享,希望可以幫助到大家,解決大家的問題,下面就開始吧!

Python有什么奇技淫巧

Python奇技淫巧

當發布python第三方package時,并不希望代碼中所有的函數或者class可以被外部import,在__init__.py中添加__all__屬性,

該list中填寫可以import的類或者函數名,可以起到限制的import的作用,防止外部import其他函數或者類

#!/usr/bin/envpython

#-*-coding:utf-8-*-

frombaseimportAPIBase

fromclientimportClient

fromdecoratorimportinterface,export,stream

fromserverimportServer

fromstorageimportStorage

fromutilimport(LogFormatter,disable_logging_to_stderr,

enable_logging_to_kids,info)

__all__=['APIBase','Client','LogFormatter','Server',

'Storage','disable_logging_to_stderr','enable_logging_to_kids',

'export','info','interface','stream']

with的魔力

with語句需要支持上下文管理協議的對象,上下文管理協議包含__enter__和__exit__兩個方法.with語句建立運行時上下文需要通過這兩個方法執行進入和退出操作.

其中上下文表達式是跟在with之后的表達式,該表示大返回一個上下文管理對象

#常見with使用場景

withopen("test.txt","r")asmy_file:#注意,是__enter__()方法的返回值賦值給了my_file,

forlineinmy_file:

printline

詳細原理可以查看這篇文章,淺談Python的with語句

知道具體原理,我們可以自定義支持上下文管理協議的類,類中實現__enter__和__exit__方法

#!/usr/bin/envpython

#-*-coding:utf-8-*-

classMyWith(object):

def__init__(self):

print"__init__method"

def__enter__(self):

print"__enter__method"

returnself#返回對象給as后的變量

def__exit__(self,exc_type,exc_value,exc_traceback):

print"__exit__method"

ifexc_tracebackisNone:

print"ExitedwithoutException"

returnTrue

else:

print"ExitedwithException"

returnFalse

deftest_with():

withMyWith()asmy_with:

print"runningmy_with"

print"------分割線-----"

withMyWith()asmy_with:

print"runningbeforeException"

raiseException

print"runningafterException"

if__name__=='__main__':

test_with()

執行結果如下:

__init__method

__enter__method

runningmy_with

__exit__method

ExitedwithoutException

------分割線-----

__init__method

__enter__method

runningbeforeException

__exit__method

ExitedwithException

Traceback(mostrecentcalllast):

File"bin/python",line34,in

exec(compile(__file__f.read(),__file__,"exec"))

File"test_with.py",line33,in

test_with()

File"test_with.py",line28,intest_with

raiseException

Exception

證明了會先執行__enter__方法,然后調用with內的邏輯,最后執行__exit__做退出處理,并且,即使出現異常也能正常退出

filter的用法

相對filter而言,map和reduce使用的會更頻繁一些,filter正如其名字,按照某種規則過濾掉一些元素

#!/usr/bin/envpython

#-*-coding:utf-8-*-

lst=[1,2,3,4,5,6]

#所有奇數都會返回True,偶數會返回False被過濾掉

printfilter(lambdax:x%2!=0,lst)

#輸出結果

[1,3,5]

一行作判斷

當條件滿足時,返回的為等號后面的變量,否則返回else后語句

lst=[1,2,3]

new_lst=lst[0]iflstisnotNoneelseNone

printnew_lst

#打印結果

1

裝飾器之單例

使用裝飾器實現簡單的單例模式

#單例裝飾器

defsingleton(cls):

instances=dict()#初始為空

def_singleton(*args,**kwargs):

ifclsnotininstances:#如果不存在,則創建并放入字典

instances[cls]=cls(*args,**kwargs)

returninstances[cls]

return_singleton

@singleton

classTest(object):

pass

if__name__=='__main__':

t1=Test()

t2=Test()

#兩者具有相同的地址

printt1,t2

staticmethod裝飾器

類中兩種常用的裝飾,首先區分一下他們

普通成員函數,其中第一個隱式參數為對象

classmethod裝飾器,類方法(給人感覺非常類似于OC中的類方法),其中第一個隱式參數為類

staticmethod裝飾器,沒有任何隱式參數.python中的靜態方法類似與C++中的靜態方法

#!/usr/bin/envpython

#-*-coding:utf-8-*-

classA(object):

#普通成員函數

deffoo(self,x):

print"executingfoo(%s,%s)"%(self,x)

@classmethod#使用classmethod進行裝飾

defclass_foo(cls,x):

print"executingclass_foo(%s,%s)"%(cls,x)

@staticmethod#使用staticmethod進行裝飾

defstatic_foo(x):

print"executingstatic_foo(%s)"%x

deftest_three_method():

obj=A()

#直接調用噗通的成員方法

obj.foo("para")#此處obj對象作為成員函數的隱式參數,就是self

obj.class_foo("para")#此處類作為隱式參數被傳入,就是cls

A.class_foo("para")#更直接的類方法調用

obj.static_foo("para")#靜態方法并沒有任何隱式參數,但是要通過對象或者類進行調用

A.static_foo("para")

if__name__=='__main__':

test_three_method()

#函數輸出

executingfoo(

executingclass_foo(

executingclass_foo(

executingstatic_foo(para)

executingstatic_foo(para)

property裝飾器

定義私有類屬性

將property與裝飾器結合實現屬性私有化(更簡單安全的實現get和set方法)

#python內建函數

property(fget=None,fset=None,fdel=None,doc=None)

fget是獲取屬性的值的函數,fset是設置屬性值的函數,fdel是刪除屬性的函數,doc是一個字符串(likeacomment).從實現來看,這些參數都是可選的

property有三個方法getter(),setter()和delete()來指定fget,fset和fdel。這表示以下這行

classStudent(object):

@property#相當于property.getter(score)或者property(score)

defscore(self):

returnself._score

@score.setter#相當于score=property.setter(score)

defscore(self,value):

ifnotisinstance(value,int):

raiseValueError('scoremustbeaninteger!')

ifvalue100:

raiseValueError('scoremustbetween0~100!')

self._score=value

iter魔法

通過yield和__iter__的結合,我們可以把一個對象變成可迭代的

通過__str__的重寫,可以直接通過想要的形式打印對象

#!/usr/bin/envpython

#-*-coding:utf-8-*-

classTestIter(object):

def__init__(self):

self.lst=[1,2,3,4,5]

defread(self):

foreleinxrange(len(self.lst)):

yieldele

def__iter__(self):

returnself.read()

def__str__(self):

return','.join(map(str,self.lst))

__repr__=__str__

deftest_iter():

obj=TestIter()

fornuminobj:

printnum

printobj

if__name__=='__main__':

test_iter()

神奇partial

partial使用上很像C++中仿函數(函數對象).

在stackoverflow給出了類似與partial的運行方式

defpartial(func,*part_args):

defwrapper(*extra_args):

args=list(part_args)

args.extend(extra_args)

returnfunc(*args)

returnwrapper

利用用閉包的特性綁定預先綁定一些函數參數,返回一個可調用的變量,直到真正的調用執行

#!/usr/bin/envpython

#-*-coding:utf-8-*-

fromfunctoolsimportpartial

defsum(a,b):

returna+b

deftest_partial():

fun=partial(sum,2)#事先綁定一個參數,fun成為一個只需要一個參數的可調用變量

printfun(3)#實現執行的即是sum(2,3)

if__name__=='__main__':

test_partial()

#執行結果

5

神秘eval

eval我理解為一種內嵌的python解釋器(這種解釋可能會有偏差),會解釋字符串為對應的代碼并執行,并且將執行結果返回

看一下下面這個例子

#!/usr/bin/envpython

#-*-coding:utf-8-*-

deftest_first():

return3

deftest_second(num):

returnnum

action={#可以看做是一個sandbox

"para":5,

"test_first":test_first,

"test_second":test_second

}

deftest_eavl():

condition="para==5andtest_second(test_first)>5"

res=eval(condition,action)#解釋condition并根據action對應的動作執行

printres

if__name__=='_

exec

exec在Python中會忽略返回值,總是返回None,eval會返回執行代碼或語句的返回值

exec和eval在執行代碼時,除了返回值其他行為都相同

在傳入字符串時,會使用compile(source,'

#!/usr/bin/envpython

#-*-coding:utf-8-*-

deftest_first():

print"hello"

deftest_second():

test_first()

print"second"

deftest_third():

print"third"

action={

"test_second":test_second,

"test_third":test_third

}

deftest_exec():

exec"test_second"inaction

if__name__=='__main__':

test_exec()#無法看到執行結果

getattr

getattr(object,name[,default])Returnthevalueof

thenamedattributeofobject.namemustbeastring.Ifthestringis

thenameofoneoftheobject’sattributes,theresultisthevalueof

thatattribute.Forexample,getattr(x,‘foobar’)isequivalentto

x.foobar.Ifthenamedattributedoesnotexist,defaultisreturnedif

provided,otherwiseAttributeErrorisraised.

通過string類型的name,返回對象的name屬性(方法)對應的值,如果屬性不存在,則返回默認值,相當于object.name

#使用范例

classTestGetAttr(object):

test="testattribute"

defsay(self):

print"testmethod"

deftest_getattr():

my_test=TestGetAttr()

try:

printgetattr(my_test,"test")

exceptAttributeError:

print"AttributeError!"

try:

getattr(my_test,"say")()

exceptAttributeError:#沒有該屬性,且沒有指定返回值的情況下

print"MethodError!"

if__name__=='__main__':

test_getattr()

#輸出結果

testattribute

testmethod

命令行處理

defprocess_command_line(argv):

"""

Returna2-tuple:(settingsobject,argslist).

`argv`isalistofarguments,or`None`for``sys.argv[1:]``.

"""

ifargvisNone:

argv=sys.argv[1:]

#initializetheparserobject:

parser=optparse.OptionParser(

formatter=optparse.TitledHelpFormatter(width=78),

add_help_option=None)

#defineoptionshere:

parser.add_option(#customizeddescription;put--helplast

'-h','--help',action='help',

help='Showthishelpmessageandexit.')

settings,args=parser.parse_args(argv)

#checknumberofarguments,verifyvalues,etc.:

ifargs:

parser.error('programtakesnocommand-linearguments;'

'"%s"ignored.'%(args,))

#furtherprocesssettings&argsifnecessary

returnsettings,args

defmain(argv=None):

settings,args=process_command_line(argv)

#applicationcodehere,like:

#run(settings,args)

return0#success

if__name__=='__main__':

status=main()

sys.exit(status)

讀寫csv文件

#從csv中讀取文件,基本和傳統文件讀取類似

importcsv

withopen('data.csv','rb')asf:

reader=csv.reader(f)

forrowinreader:

printrow

#向csv文件寫入

importcsv

withopen('data.csv','wb')asf:

writer=csv.writer(f)

writer.writerow(['name','address','age'])#單行寫入

data=[

('xiaoming','china','10'),

('Lily','USA','12')]

writer.writerows(data)#多行寫入

各種時間形式轉換

只發一張網上的圖,然后差文檔就好了,這個是記不住的

字符串格式化

一個非常好用,很多人又不知道的功能

>>>name="andrew"

>>>"mynameis{name}".format(name=name)

'mynameisandrew'

catia圖紙箭頭怎么變成實心

1.選中要變成實心的箭頭,右鍵單擊選擇“屬性”欄。2.在“線型”下拉菜單中選擇“實線”。

3.在“線寬”下拉菜單中選擇適當的實線寬度。

4.單擊“應用”按鈕,然后單擊“確定”按鈕。

5.箭頭現在應該是實心的了。

getlook like造句

1.Youwanttogetittolooklikeifitisfullofbuddies!你肯定想讓你的好友列表里存滿你的好友!

2.Now,yourPropertyGetprocedurewilllooksomethinglikethefollowing.Thelineinboldiswhatyouadded.現在你的屬性獲得程序看上去如以下。粗體字為你添加的。

3.Thesculptorhasclearlytriedhardtogetthefiguretolooklikehissubject,butthisisverydifficultandtendstomeanthesculptorenlargesthehead,ashere.

很明顯雕刻師作出努力想讓這些兵人與他的背景更相符,但是這有相當的困難以至不得不把頭做的大一些。

positivenumbers是什么意思

positivenumbern.[數]正數短語PositiveWholeNumbersBases正整數基positiverationalnumbers正有理數positiveevennumbers正偶數1.Thisiscalledthegeometricaverageandit'susedonlyforpositivenumbers.2.Thispropertysetsthecurrentlinethickness.Valuesmustbepositivenumbers.Bydefaultthisvalueissetto1.0units.這個屬性設置當前繪線的粗細。屬性值必須為正數。默認值是1.0。

Word中的域代碼有幾個

A

AddressBlock域

Advance域

Ask域

Author域

AutoNum域

AutoNumLgl域

AutoNumOut域

AutoText域

AutoTextList域

B

Bibliography域

C

Citation域

Comments域

Compare域

CreateDate域

D

Database域

Date域

DocProperty域

DocVariable域

E

Embed域

Eq字段

F

FileName域

FileSize域

Fill-In域

=(Formula)域

G

GoToButton域

GreetingLine域

H

Hyperlink域

I

If域

IncludePicture域

IncludeText域

Index域

Info域

K

Keywords域

L

LastSavedBy域

Link域

ListNum域

M

MacroButton域

MergeField域

MergeRec域

MergeSeq域

N

Next字段

NextIf域

NoteRef域

NumChars域

NumPages域

NumWords域

P

Page域

PageRef域

Print域

PrintDate域

Private域

Q

Quote域

R

RD(引用文檔)域

Ref域

RevNum域

S

SaveDate域

Section域

SectionPages域

Seq(序列)域

Set域

SkipIf域

StyleRef域

Subject域

Symbol域

T

TA(引文目錄項)域

TC(目錄項)域

模板字段

Time域

Title域

TOA(引文目錄)域

TOC(目錄)域

U

UserAddress域

UserInitials域

UserName域

X

XE(索引項)域

關于property line到此分享完畢,希望能幫助到您。

返回列表
上一篇:
下一篇: