SORU
31 Aralık 2009, PERŞEMBE


Açıklama Python'In '____' ve '___'_çıkışa girin;

bu sayfada, bu kodu gördüm

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()

teşekkürler


from __future__ import with_statement#for python2.5 

class a(object):
    def __enter__(self):
        print 'sss'
        return 'sss111'
    def __exit__(self ,type, value, traceback):
        print 'ok'
        return False

with a() as s:
    print s


print s

CEVAP
31 Aralık 2009, PERŞEMBE


Bu sihirli yöntemler (,* __enter__ *7) kullanarak kolayca kullanılabilecek nesneleri uygulamak için with deyimi ile sağlar.

Genel bir fikir kolay bazı 'cleandown' idam (try-finally bir blok gibi düşünün) kodu. ihtiyacı olan kodu oluşturmak için yapar. Some more explanation here.

Yararlı bir örnek veritabanı bağlantısı nesnesi olabilir ilgili bir kez daha sonra otomatik olarak yüklenecektir bağlantıyı kapatır (''- deyimi kapsam dışına çıkarsa ..

class DatabaseConnection(object):

    def __enter__(self):
        # make a database connection and return it
        ...
        return self.dbconn

    def __exit__(self, exc_type, exc_val, exc_tb)
        # make sure the dbconnection gets closed
        self.dbconn.close()
        ...

Yukarıda açıklandığı üzere, with deyimi ile bu nesnenin (eğer Python 2.5 eğer dosyanın üstünde from __future__ import with_statement yapmanız gerekebilir) kullanın.

with DatabaseConnection() as mydbconn:
    # do stuff

PEP434 -- The 'with' statement' de güzel bir yazı var.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Christian Atlas

    Christian At

    26 Mart 2009
  • Matthew Smith

    Matthew Smit

    24 Mayıs 2010
  • Rachel Talbott

    Rachel Talbo

    26 Ocak 2011