PDA

View Full Version : عبارت with



ASedJavad
دوشنبه 30 شهریور 1394, 15:14 عصر
سلام
کارکرد عبارت with تو پایتون چیه.
من انتظار داشتم شبیه with تو vb باشه، اما مثل اینکه کلا بحثش متفاوته.
یه سرچی هم زدم، همه جا فقط تو کار با فایل ها ازش استفاده کرده بودن. که البته من نفهمیدم چکار میکرد!

HackNetProg
دوشنبه 30 شهریور 1394, 15:45 عصر
with یک context-managers (https://docs.python.org/3.5/reference/datamodel.html#context-managers) هست برای کار کردن با منابع ای که مدیریت درس حسابی درشون نیس مثل همون فایل ها ازشون خیلی استفاده میشه.
و به عنوان مدل سینتکس شوگر از try except هم کار میکنه:





with f = opening(filename):
...read data from f...


معادل هست با



@contextmanager
def opening(filename):
f = open(filename)
try:
yield f
finally:
f.close()

یعنی به هر حال تحت هر شرایطی فابل و میبنده براتون و این خیلی مهمه.

اینم توضیحات بیشتر :


The ‘with‘ statement clarifies code that previously
would use try...finally blocks to ensure that clean-up code is executed. In this section,
I’ll discuss the statement as it will commonly be used. In the next section,
I’ll examine the implementation details and show how to write objects for use with this statement.

The ‘with‘ statement is a control-flow structure whose basic structure is:

with expression [as variable]: with-block

The expression is evaluated, and it should result in an object that supports the context
management protocol (that is, has __enter__() and __exit__() methods).




https://docs.python.org/3.5/reference/compound_stmts.html#the-with-statement
https://docs.python.org/3.5/reference/datamodel.html#context-managers
https://www.python.org/dev/peps/pep-0343/

ASedJavad
دوشنبه 30 شهریور 1394, 23:41 عصر
ممنون
ولی متأسفانه توضیحتون همون قدر برام نامفهوم بود که توضیحات اون لینکهایی که قرار داده بودید!

ahmad156
چهارشنبه 13 آبان 1394, 09:48 صبح
عبارت with زمانی استفاده میشه که از منابع مدیریت نشده داریم استفاده می کنیم مثل Stream ها.در اصل with این تضمین رو به شما میده که با پایان عبارت، منبع تخصیص یافته آزاد میشه حتی اگر خطایی رخ میده به نوعی شبیه سازی try/finally هست.
معادل عبارت using در ASP.NET و VB.NET هست