07 Python II Flashcards
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.
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.
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
# 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
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
# 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)
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
(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
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
Reparar no ( ) presente na circunferencia e ausente na area
Pode chamar de Circle.pi or self.pi
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()
»»>
?????????????
Animal Created
Dog Created
I am eating
I am an animal
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()
»»>
?????????????
Animal Created
Dog Created
I am eating
I am an animal
Herdou tudo da Classe Animal ( )
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()
»»>
?????????????
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”
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())
# raise explica que tem que colocar em cada subclasse esse termo
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
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”
Como instalar módulos no Python?
pip install package_name
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
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")
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
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
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
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
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
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