Last active
October 5, 2020 04:27
-
-
Save farisachugthai/cbd28d11594a39bd9ffa4629a7b5b8e9 to your computer and use it in GitHub Desktop.
Display what statements execute in what order in a python file, then check the doctests.
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/env python | |
# -*- coding: utf-8 -*- | |
"""Here's an interesting example of how python orders statements. | |
In addition, let's go over how initialization works as well. | |
.. code-block:: bash | |
python3 ordering.py | |
.. parsed-literal:: | |
@In [4] $ python ordering.py | |
First | |
Second | |
""" | |
class Anything: | |
"""A class that displays execution order. | |
""" | |
# These execute regardless of whether the class is instatiated or not. | |
print("First") | |
# uncommenting raises an error. Well I'll be damned. | |
# def __new__(self): | |
# print("new") | |
def __init__(self): | |
print("Init") | |
self.something = ( | |
"Some string. I believe that by making __init__ blank we" | |
"caused the class to be created with no values which" | |
"messes up initialization." | |
) | |
print("Second") | |
def meth(self): | |
print("Meth") | |
# wow a is the only instance that doesn't pop up as none | |
def normal_initialization(): | |
"""A class instantiated the typical way. | |
a = Anything() | |
Init | |
print("a instance") | |
a instance | |
print(a) | |
<__main__.Anything object at 0x77e19145b0> | |
a.meth() | |
Meth | |
""" | |
a = Anything() | |
return a | |
def messed_up_docstring(): | |
"""Idk why it doesnt work in this format. | |
>>> a = Anything() | |
Init | |
>>> print("a instance") | |
a instance | |
>>> print(a) # doctest:+ELLIPSIS | |
<__main__.Anything object at 0x...> | |
>>> a.meth() | |
Meth | |
Got it working! Needed the doctest directive because we | |
kept getting tripped up from the random output here. | |
""" | |
pass | |
# why isn't this the same thing? | |
def explicit_init(): | |
"""Explicitly call init with a string for self. | |
.. code-block:: python | |
b = Anything.__init__("foo") | |
Init | |
print("b instance") | |
b instance | |
print(b) | |
None | |
""" | |
b = Anything.__init__("foo") | |
return b | |
def instantiate_and_init(): | |
"""Instantiate the class and call it's init. | |
.. code-block:: python | |
c = Anything().__init__() | |
Init | |
Init | |
print("c instance") | |
c instance | |
print(c) | |
None | |
""" | |
c = Anything().__init__() | |
return c | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment