Hey guys am trying to use the with statement in my code..Since am new to python i just wrote to code to understand the working of with statement..My code
class Employee:
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
c = Employee("blah",1)
c.empCount = ['aad']
class Subin(Employee):
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __enter__(self):
return self
def __exit__(self ,type):
print 'ok'
def babe(self):
with c.empCount as b:
return 0
b = Subin("sds",1)
b.babe()
When I run the code I get the error:
Traceback (most recent call last):
File "C:/Python27/dfg", line 38, in <module>
b.babe()
File "C:/Python27/dfg", line 33, in babe
with c.empCount as b:
AttributeError: __exit__
Can you guys tell me why this is happening?
withkeyword does. Read the PEP-343. Please also edit your question and fix the indention of your code.withstatement is not a context manager at all - it'sc.empCount, which is a list.Subinon the other hand could (almost) be a context manager, so you'd do something likewith Subin("foo",1) as s:. But for that to have any chance of working, you'd need to fix the signature of the__exit__method first.