In [1]:
s = 'abc'

In [2]:
s.upper()


Out[2]:
'ABC'

In [3]:
# L E G B
# local
# enclosing
# global
# builtins
globals()


Out[3]:
{'FormatCode': <function yapf.yapflib.yapf_api.FormatCode>,
 'In': ['',
  u"s = 'abc'",
  u's.upper()',
  u'# L E G B\n# local\n# enclosing\n# global\n# builtins\nglobals()'],
 'Out': {2: 'ABC'},
 '_': 'ABC',
 '_2': 'ABC',
 '__': '',
 '___': '',
 '__builtin__': <module '__builtin__' (built-in)>,
 '__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__name__': '__main__',
 '__package__': None,
 '_dh': [u'/Users/reuven/Desktop'],
 '_i': u's.upper()',
 '_i1': u"s = 'abc'",
 '_i2': u's.upper()',
 '_i3': u'# L E G B\n# local\n# enclosing\n# global\n# builtins\nglobals()',
 '_ih': ['',
  u"s = 'abc'",
  u's.upper()',
  u'# L E G B\n# local\n# enclosing\n# global\n# builtins\nglobals()'],
 '_ii': u"s = 'abc'",
 '_iii': u'',
 '_oh': {2: 'ABC'},
 '_sh': <module 'IPython.core.shadowns' from '/usr/local/lib/python2.7/site-packages/IPython/core/shadowns.pyc'>,
 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x11016bb90>,
 'get_ipython': <bound method ZMQInteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x10ff5dc90>>,
 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x11016bb90>,
 's': 'abc'}

In [4]:
globals()['s']


Out[4]:
'abc'

In [5]:
s.upper()


Out[5]:
'ABC'

In [6]:
dir(s)


Out[6]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '_formatter_field_name_split',
 '_formatter_parser',
 'capitalize',
 'center',
 'count',
 'decode',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'index',
 'isalnum',
 'isalpha',
 'isdigit',
 'islower',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

In [7]:
s.title()


Out[7]:
'Abc'

In [8]:
x = 'this is a bunch of words to show to people'
x.title()


Out[8]:
'This Is A Bunch Of Words To Show To People'

In [9]:
for attrname in dir(s):
    print attrname, s.attrname


__add__
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-62f8b47659a6> in <module>()
      1 for attrname in dir(s):
----> 2     print attrname, s.attrname

AttributeError: 'str' object has no attribute 'attrname'

In [11]:
for attrname in dir(s):
    print attrname, getattr(s, attrname)


 __add__ <method-wrapper '__add__' of str object at 0x10e688418>
__class__ <type 'str'>
__contains__ <method-wrapper '__contains__' of str object at 0x10e688418>
__delattr__ <method-wrapper '__delattr__' of str object at 0x10e688418>
__doc__ str(object='') -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
__eq__ <method-wrapper '__eq__' of str object at 0x10e688418>
__format__ <built-in method __format__ of str object at 0x10e688418>
__ge__ <method-wrapper '__ge__' of str object at 0x10e688418>
__getattribute__ <method-wrapper '__getattribute__' of str object at 0x10e688418>
__getitem__ <method-wrapper '__getitem__' of str object at 0x10e688418>
__getnewargs__ <built-in method __getnewargs__ of str object at 0x10e688418>
__getslice__ <method-wrapper '__getslice__' of str object at 0x10e688418>
__gt__ <method-wrapper '__gt__' of str object at 0x10e688418>
__hash__ <method-wrapper '__hash__' of str object at 0x10e688418>
__init__ <method-wrapper '__init__' of str object at 0x10e688418>
__le__ <method-wrapper '__le__' of str object at 0x10e688418>
__len__ <method-wrapper '__len__' of str object at 0x10e688418>
__lt__ <method-wrapper '__lt__' of str object at 0x10e688418>
__mod__ <method-wrapper '__mod__' of str object at 0x10e688418>
__mul__ <method-wrapper '__mul__' of str object at 0x10e688418>
__ne__ <method-wrapper '__ne__' of str object at 0x10e688418>
__new__ <built-in method __new__ of type object at 0x10e161420>
__reduce__ <built-in method __reduce__ of str object at 0x10e688418>
__reduce_ex__ <built-in method __reduce_ex__ of str object at 0x10e688418>
__repr__ <method-wrapper '__repr__' of str object at 0x10e688418>
__rmod__ <method-wrapper '__rmod__' of str object at 0x10e688418>
__rmul__ <method-wrapper '__rmul__' of str object at 0x10e688418>
__setattr__ <method-wrapper '__setattr__' of str object at 0x10e688418>
__sizeof__ <built-in method __sizeof__ of str object at 0x10e688418>
__str__ <method-wrapper '__str__' of str object at 0x10e688418>
__subclasshook__ <built-in method __subclasshook__ of type object at 0x10e161420>
_formatter_field_name_split <built-in method _formatter_field_name_split of str object at 0x10e688418>
_formatter_parser <built-in method _formatter_parser of str object at 0x10e688418>
capitalize <built-in method capitalize of str object at 0x10e688418>
center <built-in method center of str object at 0x10e688418>
count <built-in method count of str object at 0x10e688418>
decode <built-in method decode of str object at 0x10e688418>
encode <built-in method encode of str object at 0x10e688418>
endswith <built-in method endswith of str object at 0x10e688418>
expandtabs <built-in method expandtabs of str object at 0x10e688418>
find <built-in method find of str object at 0x10e688418>
format <built-in method format of str object at 0x10e688418>
index <built-in method index of str object at 0x10e688418>
isalnum <built-in method isalnum of str object at 0x10e688418>
isalpha <built-in method isalpha of str object at 0x10e688418>
isdigit <built-in method isdigit of str object at 0x10e688418>
islower <built-in method islower of str object at 0x10e688418>
isspace <built-in method isspace of str object at 0x10e688418>
istitle <built-in method istitle of str object at 0x10e688418>
isupper <built-in method isupper of str object at 0x10e688418>
join <built-in method join of str object at 0x10e688418>
ljust <built-in method ljust of str object at 0x10e688418>
lower <built-in method lower of str object at 0x10e688418>
lstrip <built-in method lstrip of str object at 0x10e688418>
partition <built-in method partition of str object at 0x10e688418>
replace <built-in method replace of str object at 0x10e688418>
rfind <built-in method rfind of str object at 0x10e688418>
rindex <built-in method rindex of str object at 0x10e688418>
rjust <built-in method rjust of str object at 0x10e688418>
rpartition <built-in method rpartition of str object at 0x10e688418>
rsplit <built-in method rsplit of str object at 0x10e688418>
rstrip <built-in method rstrip of str object at 0x10e688418>
split <built-in method split of str object at 0x10e688418>
splitlines <built-in method splitlines of str object at 0x10e688418>
startswith <built-in method startswith of str object at 0x10e688418>
strip <built-in method strip of str object at 0x10e688418>
swapcase <built-in method swapcase of str object at 0x10e688418>
title <built-in method title of str object at 0x10e688418>
translate <built-in method translate of str object at 0x10e688418>
upper <built-in method upper of str object at 0x10e688418>
zfill <built-in method zfill of str object at 0x10e688418>

In [12]:
s.upper


Out[12]:
<function upper>

In [13]:
getattr(s, 'upper')


Out[13]:
<function upper>

In [15]:
while True:
    attrname = raw_input("Enter attribute name: ").strip()
    
    if not attrname:  # if I got an empty string
        break
    elif attrname in dir(s):
        print getattr(s, attrname)
    else:
        print "I don't know what {} is".format(attrname)


Enter attribute name: title
<built-in method title of str object at 0x10e688418>
Enter attribute name: upcase
I don't know what upcase is
Enter attribute name: asdfafafas
I don't know what asdfafafas is
Enter attribute name: 

In [16]:
s.upper


Out[16]:
<function upper>

In [17]:
s.upper()


Out[17]:
'ABC'

In [18]:
5()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-2b14d13c234b> in <module>()
----> 1 5()

TypeError: 'int' object is not callable

In [19]:
s.upper.__call__


Out[19]:
<method-wrapper '__call__' of builtin_function_or_method object at 0x10f06c710>

In [20]:
hasattr(s, 'upper')


Out[20]:
True

In [21]:
import sys

In [22]:
sys.version


Out[22]:
'2.7.13 (default, Dec 18 2016, 07:03:39) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]'

In [23]:
sys.version = '4.0.0'

In [24]:
sys.version


Out[24]:
'4.0.0'

In [25]:
def foo():
    return 5

foo.x = 100

In [26]:
def hello(name):
    return "Hello, {}".format(name)

In [27]:
hello('world')


Out[27]:
'Hello, world'

In [28]:
hello(123)


Out[28]:
'Hello, 123'

In [29]:
hello(hello)


Out[29]:
'Hello, <function hello at 0x1103f2e60>'

In [30]:
class Foo(object):
    def __init__(self, x):
        self.x = x
        
    def __add__(self, other):
        return Foo(self.x + other.x)

In [31]:
f = Foo(10)

In [32]:
f.x


Out[32]:
10

In [33]:
class Foo(object):
    pass

In [34]:
f = Foo()
f.x = 100
f.y = {'a':1, 'b':2, 'c':3}

In [35]:
vars(f)


Out[35]:
{'x': 100, 'y': {'a': 1, 'b': 2, 'c': 3}}

In [36]:
g = Foo()
g.a = [1,2,3]
g.b = 'hello'

In [37]:
vars(g)


Out[37]:
{'a': [1, 2, 3], 'b': 'hello'}

In [38]:
class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
f = Foo(10, [1,2,3])
vars(f)


Out[38]:
{'x': 10, 'y': [1, 2, 3]}

In [51]:
class Person(object):
    population = 0
    def __init__(self, name):
        self.name = name
        Person.population = self.population + 1  
    def hello(self):
        return "Hello, {}".format(self.name)

      
print "population = {}".format(Person.population)
p1 = Person('name1')
p2 = Person('name2')
print "population = {}".format(Person.population)
print "p1.population = {}".format(p1.population)
print "p2.population = {}".format(p2.population)

print p1.hello()


population = 0
population = 2
p1.population = 2
p2.population = 2
Hello, name1

In [46]:
p1.thing


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-46-a9c68ce1dae5> in <module>()
----> 1 p1.thing

AttributeError: 'Person' object has no attribute 'thing'

In [47]:
Person.thing = 'hello'

p1.thing


Out[47]:
'hello'

In [54]:
class Person(object):
    def __init__(self, name):
        self.name = name
    def hello(self):
        return "Hello, {}".format(self.name)
    
class Employee(Person):
    def __init__(self, name, id_number):
        Person.__init__(self, name)
        self.id_number = id_number
        
e = Employee('emp1', 1)
e.hello()


Out[54]:
'Hello, emp1'

In [55]:
e.hello()


Out[55]:
'Hello, emp1'

In [56]:
Person.hello(e)


Out[56]:
'Hello, emp1'
OBJECT.METHOD() # CLASS.METHOD(OBJECT)

In [57]:
s = 'abc'
s.upper()


Out[57]:
'ABC'

In [58]:
str.upper(s)


Out[58]:
'ABC'

In [59]:
type(s)


Out[59]:
str

In [60]:
id(s)


Out[60]:
4536697880

In [61]:
type(Person.hello)


Out[61]:
instancemethod

In [62]:
id(Person.hello)


Out[62]:
4564863008

In [63]:
id(Person.hello)


Out[63]:
4564980432

In [64]:
id(Person.hello)


Out[64]:
4564863408

In [65]:
Person.__dict__


Out[65]:
dict_proxy({'__dict__': <attribute '__dict__' of 'Person' objects>,
            '__doc__': None,
            '__init__': <function __main__.__init__>,
            '__module__': '__main__',
            '__weakref__': <attribute '__weakref__' of 'Person' objects>,
            'hello': <function __main__.hello>})

In [67]:
Person.__dict__['hello'](e)


Out[67]:
'Hello, emp1'

In [68]:
# descriptor protocol

In [69]:
class Thermostat(object):
    def __init__(self):
        self.temp = 20

t = Thermostat()
t.temp = 100

In [70]:
t.temp = 0

In [73]:
class Thermostat(object):
    def __init__(self):
        self._temp = 20  # now it's private!
        
    @property
    def temp(self):
        print "getting temp"
        return self._temp
    
    @temp.setter
    def temp(self, new_temp):
        print "setting temp"
        if new_temp > 35:
            print "Too high!"
            new_temp = 35
        elif new_temp < 0:
            print "Too low!"
            new_temp = 0
            
        self._temp = new_temp

t = Thermostat()
t.temp = 100
print t.temp
t.temp = -40
print t.temp


setting temp
Too high!
getting temp
35
setting temp
Too low!
getting temp
0

In [78]:
# Temp will be a descriptor!
class Temp(object):
    def __get__(self, obj, objtype):
        return self.temp
    def __set__(self, obj, newval):
        if newval > 35:
            newval = 35
        if newval < 0:
            newval = 0
        self.temp = newval

class Thermostat(object):
    temp = Temp()  # temp is a class attribute, instance of Temp
    
t1 = Thermostat()
t2 = Thermostat()

t1.temp = 100
t2.temp = 20

print t1.temp
print t2.temp


20
20

In [81]:
# Temp will be a descriptor!
class Temp(object):
    def __init__(self):
        self.temp = {}
    def __get__(self, obj, objtype):
        return self.temp[obj]
    def __set__(self, obj, newval):
        if newval > 35:
            newval = 35
        if newval < 0:
            newval = 0
        self.temp[obj] = newval

class Thermostat(object):
    temp = Temp()  # temp is a class attribute, instance of Temp
    
t1 = Thermostat()
t2 = Thermostat()

t1.temp = 100
t2.temp = 20

print t1.temp
print t2.temp


35
20

In [ ]: