07 Python II Flashcards

1
Q

Object Oriented Programming (OOP)

Allows programmers to create their own objects that have methodas and atributes

.method_name() syntax

These methods act as functions that use information about the object itself to return results, or change the current object.
Ex: appending to a list, counting the ocurrences of an element in a tuple.

A

The general format is often confusing when first encountered, and its usefulness may not be completely clear at first.

In general, OOP allows us to create code that is repeatable and organized.

For much larger scripts of Python code, functions by themselves aren’t enough for organization and repeatability.

Commonly repeated tasks and objects can be defined with OOP to create code that is more usable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
class Dog():
    def \_\_init\_\_(self, mybreed, myname, myspots):
        self.breed = mybreed   # str
        self.name = myname     # str
        self.spots = myspots   # bool
>>>>>>>>>>>>

mydog = Dog(mybreed=”Boxer”, myname=”Alf”, myspots=True)
»»»»»»

mydog.name
mydog.breed
mydog.spots
»»»»»>
‘Alf’
‘Boxer’
True

A
# Attributes
# We take in the argument
# Assign it using self.attribute_name
(Deveria estar entre 2a e 3a linha do comando)

Lembrar que convenção é substituir mybreed por breed em todos os 3 lugares, não somente em 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

class Dog():

    # CLASS OBJECT ATTRIBUTE
    # SAME FOR ANY INSTANCE OF A CLASS
animal = "Mammal"
    def \_\_init\_\_(self, mybreed, myname, myspots):
        self.breed = mybreed   # str
        self.name = myname     # str
        self.spots = myspots   # bool
>>>>>>>>
mydog = Dog("Boxer", "Alf", True)
print(mydog.name)
print(mydog.breed)
print(mydog.spots)
print(mydog.animal)
>>>>>>>>
Alf
Boxer
True
Mammal
A
# Attributes
# We take in the argument
# Assign it using self.attribute_name
(Deveria estar entre 2a e 3a linha do comando)

Lembrar que convenção é substituir mybreed por breed em todos os 3 lugares, não somente em 2

Pode colocar os parametros em ordem, não precisando citar um a um.
mydog = Dog(“Boxer”, “Alf”, True)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

class Dog():

    # CLASS OBJECT ATTRIBUTE
    # SAME FOR ANY INSTANCE OF A CLASS
animal = "Mammal"

def \_\_init\_\_(self, mybreed, myname, myspots):
        # Attributes
        # We take in the argument
        # Assign it using self.attribute_name
    self. breed = mybreed   # str
    self. name = myname     # str
    self. spots = myspots   # bool
    # OPERATIONS/ACTIONS - - - > METHODS
def bark(self, age):
        print(f"AU AU AU! My name is {self.name} and I am {age} years old!!!")
>>>>>
dogao = Dog("Boxer", "Alf", True)
print(dogao.name)
print(dogao.breed)
print(dogao.spots)
print(dogao.animal)
>>>>>>> 1

dogao.bark ( 7)
»»»> 2

A
(1)
Alf
Boxer
True
Mammal

(2)
AU AU AU! My name is Alf and I am 7 years old!!!

reparar que precisa do self.name mas no age é normal, igual nas funções

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

class Circle():

    # CLASS OBJECT ATTRIBUTE
    pi = 3.14159
def \_\_init\_\_(self, radius=1):

    self. radius = radius
    self. area = radius*radius*self.pi

# METHOD
    def circunferencia(self):
        return self.radius * Circle.pi * 2
>>>>>

circulo = Circle(100)
»»>

circulo.circunferencia ( )
»»>
628.318

circulo.area
»»>
31415.9

A

Reparar no ( ) presente na circunferencia e ausente na area

Pode chamar de Circle.pi or self.pi

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

INHERITANCE

class Animal():
    def \_\_init\_\_(self):
        print("Animal Created")
    def whoami(self):
        print("I am an animal")
    def eat(self):
        print("I am eating")
>>>>>
myanimal = Animal()
myanimal.eat()
myanimal.whoami()
>>>>>
Animal Created
I am eating
I am an animal
class Dog(Animal):
    def \_\_init\_\_(self):
        Animal.\_\_init\_\_(self)
        print("Dog Created")
>>>>>

mydog = Dog()
mydog.eat()
mydog.whoami()
»»>

?????????????

A

Animal Created
Dog Created
I am eating
I am an animal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

INHERITANCE

class Animal():
    def \_\_init\_\_(self):
        print("Animal Created")
    def whoami(self):
        print("I am an animal")
    def eat(self):
        print("I am eating")
>>>>>
myanimal = Animal()
myanimal.eat()
myanimal.whoami()
>>>>>
Animal Created
I am eating
I am an animal
class Dog(Animal):
    def \_\_init\_\_(self):
        Animal.\_\_init\_\_(self)
        print("Dog Created")
>>>>>

mydog = Dog()
mydog.eat()
mydog.whoami()
»»>

?????????????

A

Animal Created
Dog Created
I am eating
I am an animal

Herdou tudo da Classe Animal ( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

INHERITANCE

class Animal():
    def \_\_init\_\_(self):
        print("Animal Created")
    def whoami(self):
        print("I am an animal")
    def eat(self):
        print("I am eating")
>>>>>
myanimal = Animal()
myanimal.eat()
myanimal.whoami()
>>>>>
Animal Created
I am eating
I am an animal
class Dog(Animal):
    def \_\_init\_\_(self):
        Animal.\_\_init\_\_(self)
        print("Dog Created")
>>>>>

mydog = Dog()
mydog.eat()
mydog.whoami()
»»>

?????????????

A

Animal Created
Dog Created
I am eating
I am an animal

Herdou tudo da Classe Animal ( )

Se ao criar o Dog ( ) definir uma nova whoami() ou eat(), vai substituir a anterior
Pra criar novos métodos é só fazer do jeito normal, igual pra “classe mãe”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
class Animal:
    def \_\_init\_\_(self, name):    # Constructor of the class
        self.name = name
    def speak(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):

    def speak(self):
        return self.name+' says Woof!'

class Cat(Animal):

    def speak(self):
        return self.name+' says Meow!'
fido = Dog('Fido')
isis = Cat('Isis')

print(fido.speak())
print(isis.speak())

A
# raise
explica que tem que colocar em cada subclasse esse termo
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
class Conta:
    def \_\_init\_\_(self, cliente, saldo):
        self.cliente = cliente
        self.saldo = saldo
    def deposito(self, valor):
        self.saldo += valor       
    def saque(self, valor):
        if valor > self.saldo:
            print("Você não tem essa grana amigo")
        else:
            self.saldo -= valor
>>>>>>>>>

bb = Conta (“Artur”, 1000)
»»»»>
X

bb.deposito(100)
»»»»

bb.saldo
»»»»
Y

bb.saque(1200)
»»»»
Z

A

X = não retorna nada mas cria uma conta do Artur com 1000 de saldo

Y = após o depósito de 100, agora o saldo é 1100

Z = pede um saque maior que o saldo, logo vai retornar: “Você não tem essa grana amigo”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Como instalar módulos no Python?

A

pip install package_name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Como criar um módulo em Python:
(pode-se usar qualquer nome)

Criar no Visual Studio Code:

mymodule. py
myprogram. py

Escrever em mymodulo.py:
def my_func():
    print("Hey I am in mymodule.py")
Escrever em myprogram.py:
def my_func():
    print("Hey I am in mymodule.py")

Rodar Anaconda Prompt como Admin:
python myprogram.py
»»>
Hey I am in mymodule.py

A

Para criar Package:

Criar na área de trabalho a pasta:
MyMainPackage e a subpasta:
SubPackage

Colocar em cada uma delas um arquivo chamado __init__.py

Na main colocar um some_main_script.py e na sub mysubscript.py

some_main_script.py:
def report_main():
    print("Hey I am in some_main_script.py in main package")
mysubscript.py:
def sub_report():
    print("Hey Im a function inside mysubscript.py")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Como criar um módulo em Python:
(pode-se usar qualquer nome)

Criar no Visual Studio Code:

mymodule. py
myprogram. py

Escrever em mymodulo.py:
def my_func():
    print("Hey I am in mymodule.py")
Escrever em myprogram.py:
def my_func():
    print("Hey I am in mymodule.py")

Rodar Anaconda Prompt como Admin:
python myprogram.py
»»>
Hey I am in mymodule.py

A

Para criar Package:

Criar na área de trabalho a pasta:
MyMainPackage e a subpasta:
SubPackage

Colocar em cada uma delas um arquivo chamado __init__.py

Na main colocar um some_main_script.py e na sub mysubscript.py

some_main_script.py:
def report_main():
    print("Hey I am in some_main_script.py in main package")
mysubscript.py:
def sub_report():
    print("Hey Im a function inside mysubscript.py")

Criar mypackage.py na área de trabalho
from MyMainPackage import some_main_script
from MyMainPackage.SubPackage import mysubscript
some_main_script.report_main()
mysubscript.sub_report()

no Anaconda Prompt:
python mypackage.py
>>>>>>>>>>>
Hey I am in some_main_script.py in main package
Hey Im a function inside mysubscript.py
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
try:
    result3 = 10 + 10
except:
    print("ERROR ERROR ERROR")
else:
    print("Add went well")
    print(result3)
>>>>>>
Add went well
20

OBS: como não aconteceu erro pra ter except, else foi acionado

A
try:
    result3 = 10 + '10'
except:
    print("ERROR ERROR ERROR")
else:
    print("Add went well")
    print(result3)
>>>>>>>
ERROR ERROR ERROR

OBS: não dá pra somar int 10 com str ‘10’, veio erro e só leu except

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
try:
    f = open('testfile', 'w')
    f.write('Write a test line')
except TypeError:
    print("Vixi! Type Error")
except OSError:
    print("Vixi! OS Error")
finally:
    print("I always run")
>>>>>>>
I always run
A
try:
    f = open('testfile', 'r')
    f.write('Write a test line')
except TypeError:
    print("Vixi! Type Error")
except OSError:
    print("Vixi! OS Error")
finally:
    print("I always run")
>>>>>>
Vixi! OS Error
I always run

OBS: mudou w pra r

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
def askforint():
    while True:
        try:
            result = int(input("Type a Number "))
        except:
            print("Not a Number!")
            continue
        else:
            print("Thank you!")
            break
        finally:
            print("Always Run!")
>>>>>>>>

askforint ( )
»»»
Vamos supor que digitamos A e 0 (primeiro A e no segundo input 0)

Type a Number A
Not a Number!
Always Run!
Type a Number 0
Thank you!
Always Run!
A
def ask():
    while True:
        try:
            result1 = input("Type a number here: ")
            result2 = int(result1)
        except:
            print(f"{result1} is not a number")
            continue
        else:
            print("Thank you!")
            break
        finally:
            print("Who am I? Where I came from? Why I live?")
>>>>>

ask ( ) ### Primeiro Input foi a e segundo 1

Type a number here: a
a is not a number
Who am I? Where I came from? Why I live?
Type a number here: 1
Thank you!
Who am I? Where I came from? Why I live?
(no more inputs)
17
Q

DECORATORS allow you o decorate a function
Imaginar que a funçãoX faz a coisa Y e queremos uma nova função que faça Y e Z. Decorators permitem ligar e desligar a função Z na mesma funçãoX

Símbolo é @

A
def new_decorator(original_func):
    def wrap_func ( ):
        print("extra code before original function")
        original_func ( )
        print("extra code after original function")
    return wrap_func ( )
>>>>>
Vai executar print, a função externa original e mais print depois... podia ser outros códigos o lugar de print

(1)

def func_needs_decorators ( ) :
    print("I want to be decorated!!")
>>>>>

func_needs_decorators ( ) :
»»>
I wan to be decorated!!

decorated_func = new_decorator(func_needs_decorator)
>>>>>
decorated_func ( )
>>>>>
extra code before original function
I want to be decorated!!
extra code after original function

(2)

@new_decorator
def func_needs_decorators ( ) :
    print("I want to be decorated!!")
>>>>>
extra code before original function
I want to be decorated!!
extra code after original function

Resultado de (2) == (1)

Se quiser desligar o @new_decorator, é só colocar # antes

18
Q

GENERATORS FUNCTIONS -> memory efficience
Allow us to write a function that can send back a value and then later resume to pick up where it left
Allow us to generate a sequence of values over time
The main difference in syntax will be the use of a yield statmente
When a generator function is compiled they become an object that supports an iteration protocol
That means when they are called in your code they don’t actually return a value and then exit
generator functions will automatically suspend and resume their execution and state around the last point of value generation
The advatages is that instead of having to compure an entire series of values up front the generator computes one value wats until the next value is called for

For example the range () function doesn’t produce an lista in memory for all values from start to stop
Instead it just keeps track of the last number and the step size, to provied a flow of numbers

A
# Generator function for the cube of numbers (power of 3)
def gencubes(n):
    for num in range(n):
        yield num**3
>>>>>>>>
for x in gencubes(10):
    print(x)
>>>>>>>
0
1
8
27
64
125
216
343
512
729
19
Q
def genfibon(n):
    """
    Generate a fibonnaci sequence up to n
    """
    a = 0
    b = 1
    for i in range(n):
        yield a
        a,b = b,a+b
>>>>>>>

for num in genfibon(20):
print(num)
»»»»
????????

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
A

g = genfibon()
»»»>

g
»»»

print(next(g))
»»»
0

print(next(g))
»»»
1

print(next(g))
»»»
1

print(next(g))
»»»
2

print(next(g))
»»»
3

print(next(g))
»»»
5

20
Q
def gensquares(N):
    for i in range(N):
        yield i**2

for x in gensquares(10):
print(x)

A
0
1
4
9
16
25
36
49
64
81
21
Q

import random
random.randint(1,10)
»»>
3

def rand_num(low,high,n):    
    for i in range(n):
        yield random.randint(low, high)
>>>>>>

for num in rand_num(1,10,5):
print(num)
»»>
?????????

A
5
2
8
9
7

(um exemplo)

22
Q

my_list = [1,2,3,4,5]

gencomp = (item for item in my_list if item > 3)

for item in gencomp:
print(item)
»»> ?

A

4

5

23
Q

from collections import Counter
lista = [1,2,2,2,2,3,3,3,1,2,1,12,3,2,32,1,21,1,223,1]
Counter(lista)

A

Counter({1: 6, 2: 6, 3: 4, 12: 1, 32: 1, 21: 1, 223: 1})

Key é o objeto
Value é quantidade

24
Q

from collections import defaultdict
»»»>

d = defaultdict(object)
»»»>

d[‘one’]
»»»>

for item in d:
print item
»»»>
one

A

d = defaultdict(lambda: 0)
»»»>

d[‘one’]
»»»
0

d[‘two’] = 2
»»»

d
»»»»
blablabla, {‘two’: 2, ‘one’ = 0}

25
Q

import datetime

t = datetime.time(4, 20, 1)

# Let's show the different components
print(t)
print('hour  :', t.hour)
print('minute:', t.minute)
print('second:', t.second)
print('microsecond:', t.microsecond)
print('tzinfo:', t.tzinfo)

> > > > > >

A
04:20:01
hour  : 4
minute: 20
second: 1
microsecond: 0
tzinfo: None
26
Q

import datetime
t = datetime.time(4, 20, 1)

# Let's show the different components
print(t)
print('hour  :', t.hour)
print('minute:', t.minute)
print('second:', t.second)
print('microsecond:', t.microsecond)
print('tzinfo:', t.tzinfo)
>>>>>>

print(‘Earliest :’, datetime.time.min)
print(‘Latest :’, datetime.time.max)
print(‘Resolution:’, datetime.time.resolution)
»»»

A
04:20:01
hour  : 4
minute: 20
second: 1
microsecond: 0
tzinfo: None

Earliest : 00:00:00
Latest : 23:59:59.999999
Resolution: 0:00:00.000001

27
Q
today = datetime.date.today()
print(today)
print('ctime:', today.ctime())
print('tuple:', today.timetuple())
print('ordinal:', today.toordinal())
print('Year :', today.year)
print('Month:', today.month)
print('Day  :', today.day)
>>>>>>>

print(‘Earliest :’, datetime.date.min)
print(‘Latest :’, datetime.date.max)
print(‘Resolution:’, datetime.date.resolution)
»»»>

A
2018-02-05
ctime: Mon Feb  5 00:00:00 2018
tuple: time.struct_time(tm_year=2018, tm_mon=2, tm_mday=5, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=36, tm_isdst=-1)
ordinal: 736730
Year : 2018
Month: 2
Day  : 5

Earliest : 0001-01-01
Latest : 9999-12-31
Resolution: 1 day, 0:00:00

28
Q

import timeit #tempo pra processar

For loop
timeit.timeit(‘”-“.join(str(n) for n in range(100))’, number=10000)
»»»
0.24243729999989228s

List comprehension
timeit.timeit(‘”-“.join([str(n) for n in range(100)])’, number=10000)
»»»
0.21368930000016917s

Map()
timeit.timeit(‘”-“.join(map(str, range(100)))’, number=10000)
»»»
0.17011449999972683s

A

%timeit “-“.join(str(n) for n in range(100))
»»>
22.9 µs ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit “-“.join([str(n) for n in range(100)])
»»>
20.6 µs ± 106 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

29
Q

REGULAR EXPRESSIONS
import re

# List of patterns to search for
patterns = ['term1', 'term2']
# Text to parse
text = 'This is a string with term1, but it does not have the other term.'

for pattern in patterns:
print(‘Searching for “%s” in:\n “%s”\n’ %(pattern,text))

    #Check for match
    if re.search(pattern,text):
        print('Match was found. \n')
    else:
        print('No Match was found.\n')

> > > > > >

A

Searching for “term1” in:
“This is a string with term1, but it does not have the other term.”

Match was found.

Searching for “term2” in:
“This is a string with term1, but it does not have the other term.”

No Match was found.

30
Q

ADVANCED DICIONARIES

{x:x**3 for x in range(10)}

A

{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}