Skip to content

Instantly share code, notes, and snippets.

@alcides
Created April 5, 2017 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alcides/3d51b3c624c6b2b13b40999cc0dbfa23 to your computer and use it in GitHub Desktop.
Save alcides/3d51b3c624c6b2b13b40999cc0dbfa23 to your computer and use it in GitHub Desktop.
# classe Carro
# define um conjunto de atributos e metodos relativos a carros
# a completar com outras subclasses, e com mais exemplos de uso
class Carro(object):
totalDeCarros = 0 # numero total de carros criados
def __init__(self, mat, mod, a, bt):
"""Cria um carro a partir de
uma string mat,
uma string mod,
um inteiro a,
um Booleano bt.
Estes atributos supoem-se nao alteraveis.
Por omissao, o carro eh criado com velocidade 0.
A velocidade eh alteravel."""
self.matricula = mat
self.modelo = mod
self.ano = a
self.bonsTravoes = bt
self.velocidade = 0.0 # alteravel por outros metodos
Carro.totalDeCarros += 1 # atributo de classe
def verMatricula(self):
return self.matricula
def verModelo(self):
return self.modelo
def verIdade(self, anoActual):
return (anoActual + 1) - self.ano
def temBonsTravoes(self):
return self.bonsTravoes
def verVelocidade(self):
return self.velocidade
def quantosCarros(self):
return Carro.totalDeCarros
def arrancar(self, velocidadeInicial = 10.0):
self.velocidade = float(velocidadeInicial)
def travar(self):
if self.temBonsTravoes():
self.velocidade /= 1.5
else:
self.velocidade /= 1.1
def acelerar(self, aumentoVelocidade):
self.velocidade += aumentoVelocidade
def __eq__(self, other):
return self.matricula == other.matricula
def __lt__(self, other):
return self.matricula < other.matricula
def __str__(self):
if self.temBonsTravoes():
checkTravoes = "tem bons travoes"
else:
checkTravoes = "nao tem bons travoes"
return self.matricula + ', ' + self.modelo + ', ' \
+ str(self.ano) + ', ' + checkTravoes
# exemplos de uso da classe Carro
if __name__ == '__main__':
meuCarro = Carro("AB-35-67", "Mini", 1974, True)
print meuCarro
################### Definicao de outras (sub)classes
class CarroDescapotavel(Carro):
def __init__(self, matricula, mod, a, bt, capotaAberta = False):
"""Novo atributo, que eh um Booleano: capotaAberta.
Capota nasce fechada por omissao."""
Carro.__init__(self, matricula, mod, a, bt)
self.capotaAberta = capotaAberta # modificavel por outros metodos
def capotaEstahAberta(self):
return self.capotaAberta
def abrirCapota(self):
self.capotaAberta = True
# mas entao eh preciso limitar a velocidade!
if self.velocidade > 40.0:
self.velocidade = 40.0
def fecharCapota(self):
self.capotaAberta = False
def arrancar(self, velocidadeInicial = 5.0):
"Se a capota estiver aberta, limita a velocidade inicial a 5.0"
#self.velocidade = float(velocidadeInicial)
Carro.arrancar(self, velocidadeInicial)
if self.capotaAberta and self.velocidade > 5.0:
self.velocidade = 5.0
def acelerar(self, aumentoVelocidade):
"Se a capota estiver aberta, limita a velocidade a 40.0"
#self.velocidade += aumentoVelocidade
Carro.acelerar(self, aumentoVelocidade)
if self.capotaAberta and self.velocidade > 40.0:
self.velocidade = 40.0
from carro_v0 import *
c = Carro("13-KZ-22", "Phantom", 1988, True)
print c
print "Velocidade:", c.verVelocidade()
print 20 * "-"
z3 = CarroDescapotavel("13-AB-22", "Z3", 2009, True)
print z3
print "Capota esta", z3.capotaEstahAberta() and "Aberta" or "Fechada"
z3.abrirCapota()
print "Capota esta", z3.capotaEstahAberta() and "Aberta" or "Fechada"
z3.fecharCapota()
print "Capota esta", z3.capotaEstahAberta() and "Aberta" or "Fechada"
print "Velocidade:", z3.verVelocidade()
from carro_v0 import *
from person import Person
from copy import deepcopy
class MiniBus(Carro):
def __init__(self, matricula, mod, a, bt, capacidade = 9):
Carro.__init__(self, matricula, mod, a, bt)
self.capacidade = capacidade
self.passageiros = []
def getCapacidade(self):
return self.capacidade
def getPassageiros(self):
return deepcopy(self.passageiros)
def entraJose(self):
p1 = Person("Jose Silva")
self.passageiros.append(p1)
def existePassageiro(self, p):
""" p e uma Person """
existe = False
for pas in self.passageiros:
if pas.getName() == p.getName():
existe = True
return existe
def saiPassageiro(self, p):
"""
Requires: self.velocidade < 0.01 e self.existePassageiro(p)
"""
# ifs sao da versao ii)
if self.velocidade > 0.01:
raise ValueError("O minibus ainda esta a andar")
if not self.existePassageiro(p):
raise ValueError("Pessoa nao esta no minibus")
for pas in self.passageiros:
if pas.getName() == p.getName():
self.passageiros.remove(pas)
def __str__(self):
info_carro = Carro.__str__(self)
return info_carro + ", tem lugar para " + str(self.capacidade) + " pessoas"
pao_de_forma = MiniBus("AA-10-11", "Pao de Forma", 1960, False)
print pao_de_forma
jose = Person("Jose Silva")
print "jose esta:", pao_de_forma.existePassageiro(jose)
pao_de_forma.entraJose()
print "jose esta:", pao_de_forma.existePassageiro(jose)
# vai dar erro
#pao_de_forma.acelerar(10)
pao_de_forma.saiPassageiro(jose)
print "jose esta:", pao_de_forma.existePassageiro(jose)
# vai dar erro
#joao = Person("Joao Silva")
#pao_de_forma.saiPassageiro(joao)
#print "Capacidade:", pao_de_forma.getCapacidade()
#print "Passageiros:",pao_de_forma.getPassageiros()
#print "Velocidade:",pao_de_forma.verVelocidade()
# classe Person
# do livro de John Guttag, SEM exemplos de uso acrescentados no fim
#Page 97, Figure 8.2
import datetime
class Person(object):
def __init__(self, name):
"""Create a person"""
self.name = name
try:
lastBlank = name.rindex(' ')
self.lastName = name[lastBlank+1:]
except:
self.lastName = name
self.birthday = None
def getName(self):
"""Returns self's full name"""
return self.name
def __eq__(self, p):
return self.getName() == p.getName()
def getLastName(self):
"""Returns self's last name"""
return self.lastName
def setBirthday(self, birthdate):
"""Assumes birthdate is of type datetime.date
Sets self's birthday to birthdate"""
self.birthday = birthdate
def getAge(self):
"""Returns self's current age in days"""
if self.birthday == None:
raise ValueError
return (datetime.date.today() - self.birthday).days
def __lt__(self, other):
"""Returns True if self's name is lexicographically
less than other's name, and False otherwise"""
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName
def __str__(self):
"""Returns self's name"""
return self.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment