-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #5 from igui/master
Adventure 2 - Variables
- Loading branch information
Showing
72 changed files
with
2,465 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
Boilerplate | ||
----------- | ||
|
||
Insertar alguna introducción aquí. | ||
|
||
.. sourcecode:: python | ||
|
||
print('Some python code here') | ||
|
||
|
||
Desafío | ||
------- | ||
|
||
Describir el desafío aquí. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
Boilerplate | ||
----------- | ||
|
||
Insert some introduction here. | ||
|
||
.. sourcecode:: python | ||
|
||
print('Some python code here') | ||
|
||
|
||
Challenge | ||
--------- | ||
|
||
Describe the challenge here |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
.. sourcecode:: python | ||
|
||
print('Some solution here') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
"""" | ||
Boilerplate Adventure | ||
Author: Ignacio Avas ([email protected]) | ||
""" | ||
import codecs | ||
import io | ||
import sys | ||
import unittest | ||
from story.adventures import AdventureVerificationError, BaseAdventure | ||
|
||
|
||
class TestOutput(unittest.TestCase): | ||
"""Adventure test""" | ||
|
||
def __init__(self, candidate_code, file_name='<inline>'): | ||
"""Init the test""" | ||
super(TestOutput, self).__init__() | ||
self.candidate_code = candidate_code | ||
self.file_name = file_name | ||
|
||
def setUp(self): | ||
self.__old_stdout = sys.stdout | ||
sys.stdout = self.__mockstdout = io.StringIO() | ||
|
||
def tearDown(self): | ||
sys.stdout = self.__old_stdout | ||
self.__mockstdout.close() | ||
|
||
def runTest(self): | ||
"""Makes a simple test of the output""" | ||
|
||
# code = compile(self.candidate_code, self.file_name, 'exec', | ||
# optimize=0) | ||
# exec(code) | ||
self.fail("Test not implemented") | ||
|
||
|
||
class Adventure(BaseAdventure): | ||
"""Boilerplate Adventure""" | ||
title = '<Insert Title Here>' | ||
|
||
@classmethod | ||
def test(cls, sourcefile): | ||
"""Test against the provided file""" | ||
suite = unittest.TestSuite() | ||
raw_program = codecs.open(sourcefile).read() | ||
suite.addTest(TestOutput(raw_program, sourcefile)) | ||
result = unittest.TextTestRunner().run(suite) | ||
if not result.wasSuccessful(): | ||
raise AdventureVerificationError() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
Clases and Objectos | ||
------------------- | ||
|
||
Las clases son una encapsulación de estado y comportamiento, definido por | ||
variables y miembros respectivamente, en un solo tipo. Los objetos son | ||
instancias de clases que tienen sus variables y funciones desde una clase. | ||
Las clases son esencialmente una plantilla para crear objetos | ||
|
||
Una clase básica se ve como sigue: | ||
|
||
.. sourcecode:: python | ||
|
||
class Persona(object): | ||
def __init__(self, name): | ||
self.name = name | ||
|
||
def print_name(self): | ||
print("Hola {}".format(self.name)) | ||
|
||
La función especial "__init__" se llama cuando se crea un objeto Persona. | ||
Pueded definir y asignar variables que se usan dentro del objeto Persona | ||
creado. Por ejemplo la clase de arriba asigna una nueva variable dentro del | ||
objeto Persona, llamada "name" usando el valor provisto a la función | ||
__init__. El parámetro "self" hace referencia al objeto implícito que se | ||
está creando. En otros lenguajes de programación el objeto implícito se | ||
denomina "this". | ||
|
||
El siguiente código crea una instancia de Persona pasando 'Alex' a la | ||
función __init__ | ||
|
||
.. sourcecode:: python | ||
|
||
myperson = Person('Alex') | ||
|
||
En la clase Person "print_name" es una función definida por el usuario que | ||
puede ser invocada para realizar cierta tarea. La difrencia entre una | ||
función definida dentro de una clase y otra que no lo está es que las | ||
funciones definidas dentro de clases tienen acceso a las variables | ||
individuales. Esas variables son referencidas accediendo al objeto self. | ||
|
||
Para invocar una función de un objeto se puede utilizar la siguiente sintaxis. | ||
|
||
.. sourcecode:: python | ||
|
||
alex = Person('Alex') | ||
alex.print_name() # Imprime 'Hola Alex' | ||
|
||
|
||
Las variables del objeto pueden ser accedidas también utilizando una | ||
sintáxis similar: | ||
|
||
.. sourcecode:: python | ||
|
||
alex = Person('Alex') | ||
john = Person('Johnnie') | ||
print(alex.name) # Imprime 'Alex' | ||
print(john.name) # Imprime 'Johnnie' | ||
john.name = 'John Walker' | ||
print(john.name) # Imprime 'John Walker' | ||
|
||
|
||
Desafío | ||
------- | ||
|
||
Considera la clase "Vehicle" que almacena el costo de un Vehículo, y una | ||
función que retorna información acerca del vehículo como una cadena. Escribe | ||
un programa que imprima las líneas "Vehicle cost is 12000" y "Vechicle cost is | ||
5999.99" en ese orden usando la clase Vehicle y la función description | ||
|
||
.. sourcecode:: python | ||
|
||
# No modifiques este código | ||
class Vehicle: | ||
def __init__(self, cost): | ||
self.cost = cost | ||
|
||
def description(self): | ||
return "Vehicle cost is {}".format(self.cost) | ||
|
||
# Tu código va aquí | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
Classes and Objects | ||
------------------- | ||
|
||
Classes are an encapsulation of state and behaviour, defined by variables and | ||
members respectively, into a single type. Objects are instances of classes, | ||
which get their variables and functions from classes. Classes are | ||
essentially a template to create objects. | ||
|
||
A basic class would look something like this: | ||
|
||
.. sourcecode:: python | ||
|
||
class Person(object): | ||
def __init__(self, name): | ||
self.name = name | ||
|
||
def print_name(self): | ||
print("Hello {}".format(self.name)) | ||
|
||
The special "__init__" function is called when a Person object is created. | ||
It can define and assigne variables inside a created Person object. For | ||
example the class above assigns a new variable inside a Person object called | ||
name using the value provided to the __init__ function. The "self" parameter | ||
makes reference to the implicit object which was created. In other | ||
programming languages the implicit object is called "this". | ||
|
||
The following code creates an instance of Person, passing 'Alex' to the | ||
__init__ function. | ||
|
||
.. sourcecode:: python | ||
|
||
myperson = Person('Alex') | ||
|
||
In the Person class "print_name" is a user defined function that can be | ||
invoked to perform custom behaviour. The difference between a function | ||
defined inside a class an user defined function which not, is that functions | ||
inside classes do have access to the individual variables, those variables | ||
are referenced by accessing the self object. | ||
|
||
To invoke a function from an object, the following syntax can be used: | ||
|
||
.. sourcecode:: python | ||
|
||
alex = Person('Alex') | ||
alex.print_name() # Prints 'Hello Alex' | ||
|
||
|
||
Object variables can be accessed as well, by using a similar syntax | ||
|
||
.. sourcecode:: python | ||
|
||
alex = Person('Alex') | ||
john = Person('Johnnie') | ||
print(alex.name) # Prints 'Alex' | ||
print(john.name) # Prints 'Johnnie' | ||
john.name = 'John Walker' | ||
print(john.name) # Prints 'John Walker' | ||
|
||
|
||
Challenge | ||
--------- | ||
|
||
Consider a class called "Vehicle" that stores a Vehicle cost, and a | ||
function that returns information about the vehicle as an string. Write a | ||
program that prints the lines "Vechicle cost is 12000" and "Vechicle cost is | ||
5999.99" in that order using the Vehicle class and the description function | ||
|
||
.. sourcecode:: python | ||
|
||
# dont modify this code | ||
class Vehicle: | ||
def __init__(self, cost): | ||
self.cost = cost | ||
|
||
def description(self): | ||
return "Vehicle cost is {}".format(self.cost) | ||
|
||
# your code goes here | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
.. sourcecode:: python | ||
|
||
class Vehicle: | ||
def __init__(self, cost): | ||
self.cost = cost | ||
|
||
def description(self): | ||
return "Vehicle cost is {}".format(self.cost) | ||
|
||
car1 = Vehicle(12000) | ||
car2 = Vehicle(5999.99) | ||
|
||
print(car1.description()) | ||
print(car2.description()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
"""" | ||
Classes Adventure | ||
Author: Ignacio Avas ([email protected]) | ||
""" | ||
import codecs | ||
import io | ||
import sys | ||
import unittest | ||
from story.adventures import AdventureVerificationError, BaseAdventure | ||
from story.translation import gettext as _ | ||
|
||
|
||
class TestOutput(unittest.TestCase): | ||
"""Adventure test""" | ||
|
||
expected_output = "Vehicle cost is 12000\nVehicle cost is 5999.99\n" | ||
|
||
def __init__(self, candidate_code, file_name='<inline>'): | ||
"""Init the test""" | ||
super(TestOutput, self).__init__() | ||
self.candidate_code = candidate_code | ||
self.file_name = file_name | ||
|
||
def setUp(self): | ||
self.__old_stdout = sys.stdout | ||
sys.stdout = self.__mockstdout = io.StringIO() | ||
|
||
def tearDown(self): | ||
sys.stdout = self.__old_stdout | ||
self.__mockstdout.close() | ||
|
||
def runTest(self): | ||
"""Makes a simple test of the output""" | ||
|
||
# TODO check for class definition, and check if method was called | ||
code = compile(self.candidate_code, self.file_name, 'exec', optimize=0) | ||
exec(code) | ||
self.assertMultiLineEqual(self.expected_output, | ||
self.__mockstdout.getvalue(), | ||
"Should have same output" | ||
) | ||
|
||
|
||
class Adventure(BaseAdventure): | ||
"""Classes Adventure""" | ||
title = _('Classes') | ||
|
||
@classmethod | ||
def test(cls, sourcefile): | ||
"""Test against the provided file""" | ||
suite = unittest.TestSuite() | ||
raw_program = codecs.open(sourcefile).read() | ||
suite.addTest(TestOutput(raw_program, sourcefile)) | ||
result = unittest.TextTestRunner().run(suite) | ||
if not result.wasSuccessful(): | ||
raise AdventureVerificationError() |
Oops, something went wrong.