ong-z
8/23/2016 - 4:32 AM

python notes

python notes

# Check python version
python -V

import sys
sys.version

# For efficiency reasons, each module is only imported once per interpreter session. 
# Therefore, if you change your modules, you must restart the interpreter – or, if 
# it’s just one module you want to test interactively, use reload()
reload(modulename)

# When you run a Python module with
python fibo.py <arguments>
# the code in the module will be executed, just as if you imported it, but with the 
# __name__ set to "__main__". That means that by adding this code at the end of your module:
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
# you can make the file usable as a script as well as an importable module

# dir() is used to find out which names a module defines
# without arguments, dir() lists the names you have defined currently
import sys
dir(sys)

# check type
type(x)
isinstance(obj, tuple)
isinstance(obj, basestring)
isinstance(obj, int)

# print all the current properties and values of an object
from pprint import pprint
pprint (vars(your_object))

# create tuple
tuple_1 = 'aaa',
tuple_2 = ('aaa',)
tuple_3 = 'aaa','bbb'

# create list
list_1 = ['aaa']

# u'string' are unicode strings.
# call str() on a unicode string to create a regular string
>>> a = u'hello'
>>> a
u'hello'
>>> str(a)
'hello'

# ._variable is semiprivate and meant just for convention
# .__variable is often incorrectly considered superprivate, while it's actual meaning 
# is just to namemangle to prevent accidental access[1]
# .__variable__ is typically reserved for builtin methods or variables
# You can still access .__mangled variables if you desperately want to. 
# The double underscores just namemangles, or renames, the variable to something 
# like instance._className__mangled
class Test(object):
    def __init__(self):
        self.__a = 'a'
        self._b = 'b'

>>> t = Test()
>>> t._b
'b'
# t._b is accessible because it is only hidden by convention

>>> t.__a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute '__a'
# t.__a isn't found because it no longer exists due to namemangling

>>> t._Test__a
'a'
# By accessing instance._className__variable instead of just the double underscore 
# name, you can access the hidden value