Practical Python Master Class at VMWare - Day 1

Sep 26-28, 2018 Vikrant Patil

These notes are available online at http://notes.pipal.in/2018/vmware-practical-master-sep/

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

Python distribution

We will be using anaconda (python 3) distribution for this training. it can be downloaded from

https://www.anaconda.com/download/

In [1]:
2 + 3
Out[1]:
5

Warmup

In [2]:
1 + 2
Out[2]:
3
In [3]:
2**2
Out[3]:
4
In [4]:
3/4
Out[4]:
0.75
In [5]:
5//2
Out[5]:
2
In [7]:
2**10000
Out[7]:
19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376
In [8]:
4.5
Out[8]:
4.5
In [9]:
s = "There are powerful string functionalities"
In [10]:
s
Out[10]:
'There are powerful string functionalities'
In [11]:
s = 'single quote'
In [12]:
d = "double quote"
In [13]:
s
Out[13]:
'single quote'
In [14]:
d
Out[14]:
'double quote'
In [15]:
multiline = """
this is
multi line
string
"""
In [16]:
l = [1,2,3,4]
In [17]:
l[0]
Out[17]:
1
In [18]:
l[3]
Out[18]:
4
In [19]:
l[-1]
Out[19]:
4
In [20]:
s
Out[20]:
'single quote'
In [21]:
s[0]
Out[21]:
's'
In [22]:
s[-1]
Out[22]:
'e'
In [23]:
nums = [1,2,3,4,5,6,7,8,9]
In [26]:
nums[0:2]
Out[26]:
[1, 2]
In [27]:
nums = [2,4,6,8,10,12,14,16]
In [29]:
nums[3:6] # start at index 3 end at index 5
Out[29]:
[8, 10, 12]
In [30]:
s[2:5]
Out[30]:
'ngl'
In [31]:
nums[:2]
Out[31]:
[2, 4]
In [32]:
nums[5:]
Out[32]:
[12, 14, 16]
In [34]:
nums[2:4:2]
Out[34]:
[6]
In [35]:
n = list(range(3, 30, 3))
In [36]:
n
Out[36]:
[3, 6, 9, 12, 15, 18, 21, 24, 27]
In [37]:
n[3:8:2]
Out[37]:
[12, 18, 24]
In [38]:
copyofn = n[:]
In [39]:
copyofn
Out[39]:
[3, 6, 9, 12, 15, 18, 21, 24, 27]
In [40]:
n[::-1]
Out[40]:
[27, 24, 21, 18, 15, 12, 9, 6, 3]
In [41]:
word = "madam"
In [42]:
word == word[::-1]
Out[42]:
True
In [43]:
def is_palindrom(w):
    return w == w[::-1]
In [44]:
is_palindrom("madam")
Out[44]:
True
In [45]:
is_palindrom("hello")
Out[45]:
False
In [46]:
"Carefull , {0} can be {1} to health".format("breathing", "injurious")
Out[46]:
'Carefull , breathing can be injurious to health'
In [47]:
"Carefull , {arg1} can be {arg2} to health".format(arg1="breathing", arg2="injurious")
Out[47]:
'Carefull , breathing can be injurious to health'

problems

  • Print tables from 1 to 5 in nice table format
In [49]:
d = {"name":"vmware","city":"bangalore"}
In [50]:
d
Out[50]:
{'city': 'bangalore', 'name': 'vmware'}
In [51]:
d["name"]
Out[51]:
'vmware'
In [52]:
d["address"] = "J P Nagar"
In [53]:
d
Out[53]:
{'address': 'J P Nagar', 'city': 'bangalore', 'name': 'vmware'}
In [54]:
import json
In [55]:
json.dumps(d)
Out[55]:
'{"name": "vmware", "city": "bangalore", "address": "J P Nagar"}'
In [56]:
d
Out[56]:
{'address': 'J P Nagar', 'city': 'bangalore', 'name': 'vmware'}
In [57]:
l = [0,0,0,0]
In [58]:
l.append(0)
In [59]:
l
Out[59]:
[0, 0, 0, 0, 0]
In [60]:
True
Out[60]:
True
In [61]:
False
Out[61]:
False
In [62]:
bool_  = {True:1,False:0}
In [63]:
bool_[True]
Out[63]:
1

looping in python

In [64]:
for number in nums:
    print(number**2)
4
16
36
64
100
144
196
256
In [65]:
for c in "Some random string":
    print(c, end=",")
S,o,m,e, ,r,a,n,d,o,m, ,s,t,r,i,n,g,
In [66]:
for item in d:
    print(item, d[item])
name vmware
city bangalore
address J P Nagar
In [67]:
[ n*n for n in nums]
Out[67]:
[4, 16, 36, 64, 100, 144, 196, 256]
In [68]:
squares = []
for n in nums:
    squares.append(n*n)
print(squares)
[4, 16, 36, 64, 100, 144, 196, 256]
In [69]:
squares = []
for n in nums:
    squares.append(n*n)
    print(squares)
[4]
[4, 16]
[4, 16, 36]
[4, 16, 36, 64]
[4, 16, 36, 64, 100]
[4, 16, 36, 64, 100, 144]
[4, 16, 36, 64, 100, 144, 196]
[4, 16, 36, 64, 100, 144, 196, 256]
In [70]:
digits = list(range(10))
In [71]:
digits
Out[71]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [74]:
[digit*digit for digit in digits if digit%2==0]
Out[74]:
[0, 4, 16, 36, 64]
In [75]:
def even(x):
    return x%2==0
In [76]:
def odd(x):
    return not even(x)
In [77]:
[n**n for n in digits if even(n)]
Out[77]:
[1, 4, 256, 46656, 16777216]
In [78]:
x = 2 if digits[0]==0 else 1
In [79]:
x
Out[79]:
2
In [86]:
data = [[i+j for i in range(5)] for j in range(5)]
In [ ]:
 
In [87]:
data
Out[87]:
[[0, 1, 2, 3, 4],
 [1, 2, 3, 4, 5],
 [2, 3, 4, 5, 6],
 [3, 4, 5, 6, 7],
 [4, 5, 6, 7, 8]]
In [88]:
data[0]
Out[88]:
[0, 1, 2, 3, 4]
In [83]:
data[-1]
Out[83]:
[4, 5, 6, 7, 8]
In [89]:
matrix = [[i for i in range(5)] for j in range(5)]
In [90]:
matrix
Out[90]:
[[0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4]]
In [91]:
matrix[0]
Out[91]:
[0, 1, 2, 3, 4]
In [92]:
matrix[0][0]
Out[92]:
0
In [93]:
matrix[1][0]
Out[93]:
0
In [94]:
matrix[2][0]
Out[94]:
0
In [95]:
col0 = []
In [96]:
for row in matrix:
    col0.append(row[0])
In [97]:
col0
Out[97]:
[0, 0, 0, 0, 0]
In [98]:
def column(data, col):
    return [row[col] for row in data]
In [99]:
column(matrix, 0)
Out[99]:
[0, 0, 0, 0, 0]
In [100]:
column(matrix, 1)
Out[100]:
[1, 1, 1, 1, 1]

problem

  • Write a function to transpose 2d matrix.
In [101]:
setence = "Just follow the yellow brick road"
In [102]:
setence.split()
Out[102]:
['Just', 'follow', 'the', 'yellow', 'brick', 'road']
In [103]:
[ word[::-1] for word in setence.split()]
Out[103]:
['tsuJ', 'wollof', 'eht', 'wolley', 'kcirb', 'daor']
In [106]:
[column(matrix,i) for i in range(len(matrix[0]))]
Out[106]:
[[0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1],
 [2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4]]
In [109]:
def transpose(data):
    colcount = len(data[0])
    return [column(data, i) for i  in range(colcount)]
In [110]:
transpose(matrix)
Out[110]:
[[0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1],
 [2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4]]

Example quicksort

In [ ]:
 
In [119]:
def quick(data):
    if not data:
        return []
    
    p = data[0]
    less = [i for i in data[1:] if i<p]
    more = [i for i in data[1:] if i>=p]
    
    return quick(less) + [p] + quick(more)
In [120]:
quick([8, 3, 1, 1, 4, 5, 4, 5, 8])
Out[120]:
[1, 1, 3, 4, 4, 5, 5, 8, 8]
In [121]:
%%file data.csv
A1,A2,A3,A4
B1,B2,B3,B4
C1,C2,C3,C4
D1,D2,D3,D4
Writing data.csv
In [122]:
data = []
with open("data.csv") as f:
    for line in f:
        row = line.strip().split(",")
        data.append(row)
In [123]:
data
Out[123]:
[['A1', 'A2', 'A3', 'A4'],
 ['B1', 'B2', 'B3', 'B4'],
 ['C1', 'C2', 'C3', 'C4'],
 ['D1', 'D2', 'D3', 'D4']]
In [124]:
def csvparser(filename):
    data = []
    with open("data.csv") as f:
        for line in f:
            row = line.strip().split(",")
            data.append(row)
    return data
In [125]:
csvparser("data.csv")
Out[125]:
[['A1', 'A2', 'A3', 'A4'],
 ['B1', 'B2', 'B3', 'B4'],
 ['C1', 'C2', 'C3', 'C4'],
 ['D1', 'D2', 'D3', 'D4']]
In [126]:
def csvparser_(filename):
    with open("data.csv") as f:
        return [line.strip().split(",") for line in f]
In [127]:
csvparser_("data.csv")
Out[127]:
[['A1', 'A2', 'A3', 'A4'],
 ['B1', 'B2', 'B3', 'B4'],
 ['C1', 'C2', 'C3', 'C4'],
 ['D1', 'D2', 'D3', 'D4']]
In [128]:
open("data.csv").read()
Out[128]:
'A1,A2,A3,A4\nB1,B2,B3,B4\nC1,C2,C3,C4\nD1,D2,D3,D4'
In [131]:
with open("data.csv") as f:
    for line in f:
        print(line)
A1,A2,A3,A4

B1,B2,B3,B4

C1,C2,C3,C4

D1,D2,D3,D4
In [133]:
with open("data.csv") as f:
    for line in f:
        print(line.strip())
A1,A2,A3,A4
B1,B2,B3,B4
C1,C2,C3,C4
D1,D2,D3,D4
In [134]:
!ls 
data.csv   day1.ipynb  day2.ipynb  day3.ipynb  push
day1.html  day2.html   day3.html   Makefile
In [135]:
!cat data.csv
A1,A2,A3,A4
B1,B2,B3,B4
C1,C2,C3,C4
D1,D2,D3,D4

functions

In [136]:
def f():
    pass
In [137]:
print(f)
<function f at 0x7f04abe9fb70>
In [138]:
x = 3
In [139]:
y = x
In [140]:
y
Out[140]:
3
In [141]:
aliasf = f
In [142]:
print(aliasf)
<function f at 0x7f04abe9fb70>
In [143]:
def hello():
    print(hello)
In [145]:
def append(x):
    x.append(0)
In [173]:
l = []
In [174]:
append(l)
In [175]:
l
Out[175]:
[0]
In [176]:
def fun1(x):
    x = [1,2,3]
    
In [177]:
l
Out[177]:
[0]
In [178]:
fun1(l)
In [179]:
l
Out[179]:
[0]
In [180]:
def fun2(x):
    print("Before", id(x))
    x = [1,2,3]
    print("After", id(x))
    return x
    
In [181]:
print(id(l))
139658041569416
In [182]:
l = fun2(l)
Before 139658041569416
After 139658040498184
In [183]:
print(id(l))
139658040498184
In [184]:
import gc, sys
In [185]:
sys.getrefcount(l)
Out[185]:
2
In [161]:
del l
In [162]:
[id(item) for item in gc.get_referrers(l)]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-162-968976506a4f> in <module>()
----> 1 [id(item) for item in gc.get_referrers(l)]

NameError: name 'l' is not defined
In [163]:
def addition(f, items):
    return sum([f(item) for item in items])
In [164]:
def square(x):
    return x*x
In [165]:
addition(square, range(10))
Out[165]:
285
In [166]:
def identity(x):
    return x
In [167]:
addition(identity, range(10))
Out[167]:
45
In [168]:
def cube(x):
    return x**3
In [169]:
addition(cube, range(10))
Out[169]:
2025
In [186]:
max([3,4,5,61,4])
Out[186]:
61
In [187]:
words = setence.split()
In [188]:
words
Out[188]:
['Just', 'follow', 'the', 'yellow', 'brick', 'road']
In [189]:
max(words)
Out[189]:
'yellow'
In [191]:
numbers = ["one", "two","three","four","five"]
In [194]:
max(numbers) # by dictionary order
Out[194]:
'two'
In [193]:
max(numbers, key=len)
Out[193]:
'three'
In [202]:
records = [
    ("A1",0.3,90),
    ("A2",0.5,80),
    ("A3",0.1,95),
    ("A4",0.35,85),
    ("A5",0.34,82)
]
In [203]:
min(records)
Out[203]:
('A1', 0.3, 90)
In [204]:
max(records)
Out[204]:
('A5', 0.34, 82)
In [205]:
for record in records:
    print(record)
('A1', 0.3, 90)
('A2', 0.5, 80)
('A3', 0.1, 95)
('A4', 0.35, 85)
('A5', 0.34, 82)
In [206]:
def column0(r):
    return r[0]
In [207]:
def column1(r):
    return r[1]
def column2(r):
    return r[2]
In [208]:
max(records, key=column1)
Out[208]:
('A2', 0.5, 80)
In [209]:
max(records, key=column2)
Out[209]:
('A3', 0.1, 95)

returning functions

In [210]:
def make_adder(x):
    
    def adder(y):
        return x+y
    
    return adder
In [211]:
adder5 = make_adder(5)
In [212]:
adder5
Out[212]:
<function __main__.make_adder.<locals>.adder>
In [213]:
adder5(6)
Out[213]:
11
In [214]:
adder5(4)
Out[214]:
9
In [215]:
adder5(3)
Out[215]:
8
In [217]:
def make_log_helper(level):
    
    def log(msg):
        print(level.upper(),":",msg)
    
    return log
In [218]:
info = make_log_helper("info")
In [219]:
error = make_log_helper("error")
In [220]:
warning = make_log_helper("warning")
In [221]:
info("This is just for your information")
INFO : This is just for your information
In [222]:
error("Err, humans always make mistake!")
ERROR : Err, humans always make mistake!
In [223]:
warning("Be carefull, you live in city!")
WARNING : Be carefull, you live in city!
In [224]:
level = "info"
In [225]:
info_ = make_log_helper(level)
In [226]:
del level
In [227]:
info_("Just another info")
INFO : Just another info
In [228]:
def volume_cylinder(radius=1.0, height=1.0):
    return 3.14*radius**2*height
In [230]:
volume_cylinder() # radius = 1, height = 1
Out[230]:
3.14
In [231]:
volume_cylinder(1)
Out[231]:
3.14
In [232]:
volume_cylinder(1,2)
Out[232]:
6.28
In [233]:
volume_cylinder(height=1,radius=2)
Out[233]:
12.56
In [234]:
add = lambda x,y: x+y
In [235]:
add(2,3)
Out[235]:
5
In [236]:
def make_adder(x):
    
    return lambda y: x+y
In [237]:
adder7 = make_adder(7)
In [238]:
adder7(5)
Out[238]:
12
In [239]:
def column(c):
    return lambda record:record[c]
In [240]:
max(records, key=column(0))
Out[240]:
('A5', 0.34, 82)
In [241]:
max(records, key=column(1))
Out[241]:
('A2', 0.5, 80)
In [242]:
max(records, key=column(1))
Out[242]:
('A2', 0.5, 80)
In [243]:
records
Out[243]:
[('A1', 0.3, 90),
 ('A2', 0.5, 80),
 ('A3', 0.1, 95),
 ('A4', 0.35, 85),
 ('A5', 0.34, 82)]
In [252]:
max([1,2,3,4], key=column(0))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-252-f80a79de73f3> in <module>()
----> 1 max([1,2,3,4], key=column(0))

<ipython-input-239-0324051136c9> in <lambda>(record)
      1 def column(c):
----> 2     return lambda record:record[c]

TypeError: 'int' object is not subscriptable

decorators

In [244]:
def add(x,y):
    return x+y
In [245]:
def debug(f):
    
    def wrapper(*args):
        print("Begin ", f.__name__)
        r = f(*args)
        print("End ", f.__name__)
        return r
    
    return wrapper
In [246]:
add1 = debug(add)
In [247]:
add(2,3)
Out[247]:
5
In [248]:
add1(2,3)
Begin  add
End  add
Out[248]:
5
In [249]:
add = debug(add)
In [250]:
add(2,3)
Begin  add
End  add
Out[250]:
5
In [251]:
@debug
def square(x):
    return x

problem

  • Write a decorator called depricated which when applied to a function shows depricated warning
In [253]:
from functools import partial

Classes

In [254]:
import math
In [255]:
math.pi
Out[255]:
3.141592653589793
In [256]:
math.sqrt(2)
Out[256]:
1.4142135623730951
In [259]:
%%file bank0.py

balance = 0

def get_balance():
    return balance

def withdraw(amount):
    global balance
    balance -= amount
    
def deposite(amount):
    global balance
    balance += amount
    
    
Overwriting bank0.py
In [261]:
import bank0 as bankaccount
In [262]:
bankaccount.get_balance()
Out[262]:
0
In [263]:
bankaccount.deposite(100)
In [264]:
bankaccount.get_balance()
Out[264]:
100
In [265]:
import bank0 as bankaccount1
In [266]:
bankaccount1.get_balance()
Out[266]:
100
In [267]:
%%file bank1.py

def make_account():
    return {"balance":0}

def get_balance(account):
    return account['balance']

def withdraw(account,amount):
    account['balance'] -= amount
    
def deposite(account, amount):
    account['balance'] += amount
    
    
Writing bank1.py
In [268]:
import bank1 as bank
In [269]:
a1 = bank.make_account()
In [270]:
bank.get_balance(a1)
Out[270]:
0
In [271]:
bank.deposite(a1, 200)
In [272]:
bank.get_balance(a1)
Out[272]:
200
In [273]:
class BankAccount:
    
    def __init__(self):
        self.balance = 0
        
    def get_balance(self):
        return self.balance
    
    def withdraw(self, amount):
        self.balance -= amount
        
    def deposit(self, amount):
        self.balance += amount
In [274]:
a = BankAccount()
In [275]:
type(a)
Out[275]:
__main__.BankAccount
In [277]:
type(BankAccount)
Out[277]:
type
In [278]:
class Foo:
    
    def foo1():
        print("foo1")
        
    @staticmethod
    def foo2():
        print("foo2")
In [279]:
Foo.foo1()
foo1
In [280]:
Foo.foo2()
foo2
In [281]:
f = Foo()
In [282]:
f.foo2()
foo2
In [283]:
f.foo1()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-283-d11d3b17f5aa> in <module>()
----> 1 f.foo1()

TypeError: foo1() takes 0 positional arguments but 1 was given
In [284]:
a.get_balance()
Out[284]:
0
In [285]:
a.deposit(300)
In [286]:
a.get_balance()
Out[286]:
300
In [287]:
type(Foo.foo1)
Out[287]:
function
In [288]:
type(Foo.foo2)
Out[288]:
function
In [289]:
type(a.get_balance)
Out[289]:
method
In [290]:
type(BankAccount.get_balance)
Out[290]:
function
In [291]:
class Point:
    x,y = 0,0
    
    def __init__(self, color):
        self.color = color
        
    def getcolor(self):
        return self.color
In [292]:
Point.x
Out[292]:
0
In [293]:
Point.y
Out[293]:
0
In [294]:
Point.__init__
Out[294]:
<function __main__.Point.__init__>
In [295]:
Point.getcolor
Out[295]:
<function __main__.Point.getcolor>
In [297]:
p = Point("red")
In [298]:
p.x
Out[298]:
0
In [299]:
p.y 
Out[299]:
0
In [300]:
p.color
Out[300]:
'red'
In [301]:
Point.color
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-301-78328dc5d629> in <module>()
----> 1 Point.color

AttributeError: type object 'Point' has no attribute 'color'
In [302]:
Point.x 
Out[302]:
0
In [303]:
p.x
Out[303]:
0
In [304]:
p1 = Point("yellow")
In [305]:
p1.x
Out[305]:
0
In [306]:
Point.x = 10
In [307]:
p.x
Out[307]:
10
In [308]:
p1.x
Out[308]:
10
In [309]:
p.x = 20
In [310]:
Point.x
Out[310]:
10
In [311]:
p.x
Out[311]:
20
In [312]:
p1.x
Out[312]:
10
In [313]:
p.__dict__
Out[313]:
{'color': 'red', 'x': 20}
In [314]:
p1.__dict__
Out[314]:
{'color': 'yellow'}
In [315]:
Point.__dict__
Out[315]:
mappingproxy({'__dict__': <attribute '__dict__' of 'Point' objects>,
              '__doc__': None,
              '__init__': <function __main__.Point.__init__>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Point' objects>,
              'getcolor': <function __main__.Point.getcolor>,
              'x': 10,
              'y': 0})
In [316]:
p.z = 10
In [317]:
p.__dict__
Out[317]:
{'color': 'red', 'x': 20, 'z': 10}
In [318]:
p1.__dict__
Out[318]:
{'color': 'yellow'}
In [319]:
Point.__dict__
Out[319]:
mappingproxy({'__dict__': <attribute '__dict__' of 'Point' objects>,
              '__doc__': None,
              '__init__': <function __main__.Point.__init__>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Point' objects>,
              'getcolor': <function __main__.Point.getcolor>,
              'x': 10,
              'y': 0})
In [320]:
del p.x
In [321]:
p.__dict__
Out[321]:
{'color': 'red', 'z': 10}
In [322]:
p.x
Out[322]:
10

Customizing classes

In [323]:
l = [1,2,2]
In [324]:
l
Out[324]:
[1, 2, 2]
In [325]:
p
Out[325]:
<__main__.Point at 0x7f04abc6d7f0>
In [326]:
class Pair:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
In [327]:
p = Pair(1,2)
In [329]:
p
Out[329]:
<__main__.Pair at 0x7f04abead400>
In [366]:
class Pair:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def __repr__(self):
        return "Pair({0.x!r},{0.y!r})".format(self)
    
    def __str__(self):
        return "<{0.x!s} {0.y!s}>".format(self)
    
    def __add__(self, p):
        return Pair(self.x+p.x, self.y+p.y)
    
    def __getitem__(self, name):
        if name == "x":
            return self.x
        elif name == "y":
            return self.y
        else:
            raise AttributeError("No such attribute, " + name)
In [351]:
Pair(1,2)
Out[351]:
Pair(1,2)
In [352]:
print(Pair(1,2))
<1 2>
In [353]:
a
Out[353]:
<__main__.BankAccount at 0x7f04abe0bcf8>
In [354]:
print(a)
<__main__.BankAccount object at 0x7f04abe0bcf8>
In [355]:
"hello " + "World!"
Out[355]:
'hello World!'
In [356]:
s = "hello"
In [357]:
s *2
Out[357]:
'hellohello'
In [358]:
2 *s
Out[358]:
'hellohello'
In [367]:
p1 = Pair(1,2)
In [368]:
p2 = Pair(3,4)
In [369]:
p1 + p2
Out[369]:
Pair(4,6)
In [370]:
p1['x']
Out[370]:
1
In [371]:
class Foo:
    
    def __setattr__(self, name, value):
        raise Exception("No way!")
        
In [372]:
f = Foo()
In [373]:
f.x = 10
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-373-6f53f5cd338a> in <module>()
----> 1 f.x = 10

<ipython-input-371-07810304a843> in __setattr__(self, name, value)
      2 
      3     def __setattr__(self, name, value):
----> 4         raise Exception("No way!")
      5 

Exception: No way!
In [375]:
Foo.x = 10
In [376]:
f = Foo()
In [377]:
f.x
Out[377]:
10
In [378]:
class Special:
    
    __slots__ =['x','y']
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
In [379]:
s = Special(1,2)
In [380]:
s.z = 10
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-380-373a10c4d1a9> in <module>()
----> 1 s.z = 10

AttributeError: 'Special' object has no attribute 'z'
In [ ]: