Professional Documents
Culture Documents
def __str__(self):
return ("Title: {}, Author: {}, pages: {}".format(self.title,self.author,self.
def __len__(self):
return self.pages
def __repr__(self):
return ("Book({!r}, {!r}, {!r})".format(self.title, self.author, self.pages))
def __del__(self):
print("A Book is Destroyed")
def __hello__(self):
print("Hello World")
A Book is Created
In [102]: len(book)
Out[102]: 145
In [22]: str(book)
In [23]: repr(book)
1
In [24]: print(book)
In [ ]:
In [2]: func()
Out[2]: 1
def func():
print(locals())
In [5]: print(globals().keys())
In [7]: print(globals()['s'])
In [8]: func()
{}
In [15]: hello()
In [17]: greet
2
In [18]: greet()
In [21]: hello()
---------------------------------------------------------------------------
<ipython-input-21-a803225a2f97> in <module>()
----> 1 hello()
In [22]: greet()
def greet():
return ("\t This is inside the greet() function")
def welcome():
return("\t This is inside the welcome() function")
print(greet())
print(welcome())
print("Now we are back inside the hello() function")
In [25]: hello()
In [26]: welcome()
3
---------------------------------------------------------------------------
<ipython-input-26-efaf77b113fd> in <module>()
----> 1 welcome()
def greet():
return ("\t This is inside the greet() function")
def welcome():
return("\t This is inside the welcome() function")
In [30]: x = hello()
In [31]: x
In [32]: print(x())
In [39]: other(hello)
4
In [48]: def new_decorator(func):
def wrap_func():
print('Code here, before executing the func()')
func()
return wrap_func
In [51]: func_needs_decorator()
In [52]: @new_decorator
def func_needs_decorator():
print("This function needs a decorator")
In [53]: func_needs_decorator()
0
1
8
27
64
125
216
343
512
729
5
In [56]: def genfibon(n):
a = 1
b = 1
for i in range(n):
yield a
a,b = b, a+b
1
1
2
3
5
8
13
21
34
55
In [59]: g = simple_gen()
In [60]: print(next(g))
In [61]: print(next(g))
In [62]: print(next(g))
In [65]: s = 'hello'
for x in s:
print(x)
6
h
e
l
l
o
---------------------------------------------------------------------------
<ipython-input-67-8f0cf519e20b> in <module>()
1 # String is "Iterable" but is not Iterator
----> 2 next(s)
In [70]: next(s_iter)
Out[70]: 'h'
In [71]: next(s_iter)
Out[71]: 'e'
In [72]: next(s_iter)
Out[72]: 'l'
In [73]: next(s_iter)
Out[73]: 'l'
In [74]: next(s_iter)
Out[74]: 'o'
In [76]: # Everything you can use "for... in..." on is an iterable; lists, strings, files...
# These iterables are handy because you can read them as much as you wish,
# but you store all the values in memory and
# this is not always what you want when you have a lot of values.
7
In [77]: # Generators are iterators, a kind of iterable you can only iterate over once.
# Generators do not store all the values in memory, they generate the values on the fly
In [79]: # When you call the function, the code you have written in the function body does not r
# The function only returns the generator object, this is a bit tricky
# Then, your code will be run each time the for uses the generator.
def mygenerator():
for x in range(3):
yield x
0
1
2
In [84]: # The first time the for calls the generator object created from your function,
# it will run the code in your function from the beginning until it hits yield,
# then it'll return the first value of the loop.
# Then, each other call will run the loop you have written in the function one more tim
# and return the next value, until there is no value to return.
In [87]: #Counter
from collections import Counter
In [90]: l = [1,1,1,2,4,4,5,1,2,3,12,3,2,1,2,3,1,2,3,4,2,1,2,3]
Counter(l)
In [91]: s = 'asssvacbvvaasssdjessses'
Counter(s)
Out[91]: Counter({'a': 4, 'b': 1, 'c': 1, 'd': 1, 'e': 2, 'j': 1, 's': 10, 'v': 3})
In [93]: s = 'How many times does each word show up in this sentence word word show up in the'
8
Out[95]: Counter({'How': 1,
'does': 1,
'each': 1,
'in': 2,
'many': 1,
'sentence': 1,
'show': 2,
'the': 1,
'this': 1,
'times': 1,
'up': 2,
'word': 3})
In [98]: my_function.__doc__
In [99]: dir(Counter)
Out[99]: ['__add__',
'__and__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__iand__',
'__init__',
'__init_subclass__',
'__ior__',
'__isub__',
'__iter__',
'__le__',
'__len__',
'__lt__',
9
'__missing__',
'__module__',
'__ne__',
'__neg__',
'__new__',
'__or__',
'__pos__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'__weakref__',
'_keep_positive',
'clear',
'copy',
'elements',
'fromkeys',
'get',
'items',
'keys',
'most_common',
'pop',
'popitem',
'setdefault',
'subtract',
'update',
'values']
In [103]: dir(book)
Out[103]: ['__class__',
'__del__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__hello__',
10
'__init__',
'__init_subclass__',
'__le__',
'__len__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'author',
'pages',
'title']
In [104]: book.__class__
Out[104]: __main__.Book
In [105]: book.__dir__
In [106]: dir(list)
Out[106]: ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
11
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
class Mallard(object):
def quack(self):
print ("Quack Quack")
def shoot(bird):
bird.quack()
Quack
Quack Quack
12
In [110]: calc(2,3)
Out[110]: 5
In [111]: calc('2','3')
Out[111]: '23'
In [112]: calc([2],[3])
Out[112]: [2, 3]
a = Foo()
b = Foo()
print(a)
print(b)
Hello
Hello
<__main__.Foo object at 0x7f03b0b19c18>
<__main__.Foo object at 0x7f03b0b19be0>
13
In [7]: name = 'Subash'
a = []
a.append(name)
b = a
b.append('Basnet')
name = 'Nabin'
print (name, a, b)
first_names.append('Igor')
In [13]: print(name_tuple)
In [14]: A = ['x','y','z']
B = ['X', 'Y', 'Z']
AB = (A,B)
A.append('w')
print(AB)
answer_list = []
foo(answer_list)
print(answer_list)
[42]
[42]
14
answer_list = 'old value'
foo(answer_list)
print(answer_list)
new value
old value
In [27]: a
In [28]: b
In [29]: a is b
Out[29]: False
In [30]: # Because our test object uses immutable types (ints) for its coordinates,
# theres no difference between a shallow and
# a deep copy in this case.
def __repr__(self):
return (f'Rectangle({self.topleft!r}, '
f'{self.bottomright!r})')
In [33]: rect
15
Out[33]: Rectangle(Point(0, 1), Point(5, 6))
In [34]: srect
Out[35]: False
In [37]: rect
In [38]: srect
In [41]: drect
In [42]: rect
In [43]: srect
In [ ]:
16