Last active
August 29, 2015 14:15
-
-
Save keriszafir/5fb426b3d18306f4d90f to your computer and use it in GitHub Desktop.
OOP with context test and explanation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
class Foo(object): | |
def __init__(self): | |
print('Initializing Foo') | |
def __enter__(self): | |
print('Entering Foo context') | |
return self | |
def __exit__(self, *args): | |
print('Exiting Foo context') | |
def Foomethod(self): | |
print('Called Foomethod') | |
class Bar(object): | |
def __init__(self, other): | |
self.other = other | |
print('Initializing Bar') | |
def __enter__(self): | |
print('Entering Bar context') | |
return self | |
def __exit__(self, *args): | |
print('Exiting Bar context') | |
def Barmethod(self): | |
print('Called Barmethod') | |
def Foomethodfrombar(self): | |
print('Calling Foomethod from Bar class') | |
self.other.Foomethod() | |
print('Called Foomethod from Bar class') | |
if __name__ == '__main__': | |
foo = Foo() | |
with Foo() as foo, Bar(foo) as bar: | |
print 'foo is an instance of ', type(foo) | |
print 'bar is an instance of ', type(bar) | |
foo.Foomethod() | |
bar.Barmethod() | |
bar.Foomethodfrombar() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment