Please enable JavaScript.
Coggle requires JavaScript to display documents.
PYTHON everything is an object USE DEEPCOPY() !!! How are arguments…
PYTHON
everything is an object
USE DEEPCOPY() !!!
How are arguments passed
— by reference or by value?
If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart’s delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you’re done, the outer reference will still point at the original object.
LIST
ex.["1",2]
[] , list() from TUPLE,STR,DICT
mutable
ordered
every element is not unique
.union, + LIST []
LIST[index]=value
LIST[start:stop:step] # < stop
LIST[n:n]=LIST1 # insert in position n LIST1
+ LIST
LIST * N
del LIST[id]
del LIST[start:stop]
LIST[index1:index2]=[value1,...,valuen]
# can insert into position
.append(object)
.extend(iterable)
.insert(index, object)
.remove(object) # with Exception
.pop(id)
.clear
.sort(key=function,reversed=..)
[ element if element.. x else y for element in ... if element.. z ]
# list comprehension
.reverse
.sort
.index
# search element
DICT
ex.{"1":2,}
{} , dict() from DICT,LIST_of_TUPLES, key=value
mutable
unordered
key is unique
del
DICT[key]
DICT[key]=value
# add new key or update value
.clear
.get(key)
# return value or None
.get(key,default)
# return value or default
.items
.keys
.values
.pop(key)
# with Exception
.pop(key,default)
# without Exception
.popitem(key)
# return (key,value)
.update
(DICT or LIST_of_TUPLES or key=value)
.setdefault(key,default)
TUPLE
ex.("1",2)
() , tuple()
immutable
ordered
every element is not unique
TUPLE[index]
(v1,...vn)=TUPLE
TUPLE=v1,...vn
SET
ex.{"1",2}
set() from LIST, TUPLE, STR : :
mutable
unordered
every element is unique and immutable (can't be LIST or DICT)
.union, | SET
.clear
.pop()
# remove random with Exception
.discard(element)
without Exception
.remove(element)
with Exception
.add(element)
> SET
.issuperset, >= SET
< SET
.issubset, <= SET
.isdisjoint
#no common elements
.symmetric_difference, ^ SET, symmetric_difference_update
.difference, - SET, .difference_update
.intersection, & SET, .intersection_update
.update
FROZENSET
frozenset()
immutable
unordered
every element is unique and immutable (can't be LIST or DICT)
FUNCTIONS
len
in
not in
min
max
id
hush
is
# True if equal
all(iterable)
# False if bool(element_i)==False
any(iterable)
# True if bool(element_i)==True
filter(function,iterable)
# filter by bool(function(element))
enumerate(iterable)
# for i,element from enumerate(iterable)
map(function,iterable)
# convert to function(element)
slice(start,stop,step)
# make slice class. iterable[slice(..)]
sorted(iterable,key=function,reverse=..)->LIST
MATH
abs()
pow(x,y) # x in degree of y
quit()
PRINT
print(v1,..,vn,end='..',sep='..')
print(f'...{var}')
print("..{}".format(var))
print('.. %0.2f' %var)
'{:,}'.format({1000000)
# 1,000,000
STR
ex "123"
"", ''
immutable
ordered
.find(subst)
# return index
.join()
# ', '.join(["1","2"])=="1, 2"
.replace(subst,text)
# does not change the STR
.split(substr)
+ STR
STR * N
STR[index]
.strip
.lower
.upper
"{} .. {}".format(var1,..,varn)
.translate
(str.maketrans("", "", punctuation))
lambda
x : x+1
DATETIME
.today()
.strftime("format")
# "%d/%m/%Y , daatetime to STR
.strptime(STR,format)
# STR to datetime
.timedelta(..)
# + days, seconds, etc.
.datetime(year,month,day,..)
.isoformat
# to STR
.fromisoformat
# from STR to datetime
CLASS
Attributes of an object can be created on the fly.
Doesn't support Method Overloading by default
Derived class method "overrides" the method provided in the base class.
new
, then
init
# instance = super(MyClass, cls).
new
(cls,
args, **kwargs)
or instance = object.
new
(cls,
args, **kwargs)
__doc__
# docstring of class
self
__init__()
del CLASS.attr
del CLASS
__class__
super()
# to run smth from parent class
_ PROTECTED , __ PRIVATE
isinstance(obj,CLASS)
issubclass(CLASS,CLASS)
__mro__ , mro()
# Method Resolution Order (MRO)
__str__
__add__
__sub__
__mul__
__pow__
__truediv__
__floordiv__
__mod__
__lshift__
__rshift__
__and__
__or__
__xor__
__invert__
__repr__
__lt__
__le__
__lq__
__ne__
__gt__
__ge__
@staticmethod @abstractmethod
hasattr
(class,attr_name)
__dict__
# attrs of class
json
.dumps
.loads
constructions
match var:
case val:
case val:
default val:
while ..:
if ..:
elif:
else:
for ... in....:
FILE
open
# 'r','w','w+'
read
readline
writelines(LIST) # does not put '\n'
write
close
RANDOM
randint
seed
randrange # end range not inclusive
random # float, 0<=..<1
choice(LIST)
TKINTER
is python built-in GUI framework
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
window.resizable(0, 0)
window.title("...")
window.
mainloop
WIDGETS
master= # window, frame
Text
# get("1.0",tk.END), delete, insert("1.0", "..")
Label
lbl= tk.Label(master=window, text="0",..
lbl["text"]=...
Button
command=
Entry
# get, delete, insert
frame = tk.
Frame
()
LAYOUT
geometry managers
pack
# for simple layout
fill=
# None,X,Y,BOTH
side=
# tk.LEFT, tk.RIGHT, tk.TOP, tk.BOTTOM
expand=
# True
place
# x=.., y=..
grid
window.columnconfigure(0, weight=1)
padx, pady
# extra space
row, column
sticky
# tk.E, tk.N, tk.W, tk.S, tk.EW..
ipadx, ipady
# inside widgeet borders
columnspan
# unite some columns
bind
window.bind("<Left>", handle_left_key_press)
optimize
&
test
from sys import
getsizeof
comp = [i for i in range(10000)]
gen = (i for i in range(10000))
x = getsizeof(comp)
print("x = ", x)
y = getsizeof(gen)
print("y = ", y)
from
timeit
import
timeit
print(timeit('''list_com = [i for i in range(100) if i % 2 == 0]''', number=1000000))
BeautifulSoup
(text,"html.parser")
bs4
.find
.find_all
# txt,attrs={"..","..")
.string
[".."]
# value of attribute
.prettify()
csv
.writer
.reader
.DictReader
for line_dict in csv.DictReader(file, delimiter=',', quotechar='"'):
line_dict[..key..]
.DictWriter
csv.writer(file,delimiter=',', quotechar='"').writerow(..keys..)
csv.DictWriter(file,delimiter=',', quotechar='"',fieldnames=...).writerows(DICT)
import copy
copy.deepcopy(obj)
# real copy of object