jeroeningelbrecht

View on GitHub
created at: 9 August 2019
[home]

Python Cheat sheet

by jeroen

Python cheat sheet

Introspection and Reflection

__dict__

scope

what

examples

examples/dictEx.py

class Example:
    counter = 0

    def __init__(self, val=1):
        self.__val = val


e = Example()

Example.__dict__ # {'__module__': '__main__', 'counter': 0, '__init__': <function Example.__init__ at 0x7fb01b097ea0>, '__dict__': <attribute '__dict__' of 'Example' objects>, '__weakref__': <attribute '__weakref__' of 'Example' objects>, '__doc__': None}

e.__dict__ # {'_Example__val': 1}
    

__name__

scope

what

Identify the module in the import system

examples

# package foo.bar
# module name: module.py
def print_name():
    print(__name__)
    
print_name()
# prints: '__main__'
from foo.bar.module import print_name

print_name() # function defined in the imported module.py
# prints: 'module' <> '__main__' when executed in the module.py file itself ^^

type(obj)

scope

what

returns the class of the object

example

class Example:
    pass
    

e = Example()
type(e)  # prints "<class '__main__.Example'>"
[home]
tags: [python] [string] [introspection] [reflection] [inheritance]