Skip to content

Instantly share code, notes, and snippets.

@joetechem
Last active March 13, 2017 22:01
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 joetechem/bfea2890ef9493cdd0d81208106de7ff to your computer and use it in GitHub Desktop.
Save joetechem/bfea2890ef9493cdd0d81208106de7ff to your computer and use it in GitHub Desktop.
using basic object-oriented programming to define a 'real-world' class of modern computers
# Python 2.7
# CREATING AND USING A CLASS
# You can model almost anything using classes. Let's start by writing a simple
# class, Computer, that represents a modern computer --not one computer in particular, but any modern computer.
# What do we know about most modern computers?
# They have a name and can store memory.
# and many computers can take input and display input.
# The two pieces of information (name and memory capacity)
# and the two behaviors (input and output) can go in the class Computer,
# because they are common to most computers (modern ones).
# This class will tell Python how to make an object representing a computer.
# After this class is written, we'll use it to make individual instances,
# each of whcih represents one specific computer.
class Computer():
"""A simple attempt to model a modern computer."""
def __init__(self, name, memory):
"""Initialize name and age attributes."""
self.name = name
self.memory = memory
def take_input(self):
"""Simulate a computer accepting input in response to a given command."""
print(self.name.title() + " is now accepting input.")
def display_output(self):
"""Simulate displaying information in response to input."""
print(self.name.title() + " displayed output!")
# MAKING AN INSTANCE FROM A CLASS
# Let's make an instance representing a specific computer:
my_computer = Computer('TRS-80', 16)
print("My computer's name is " + my_computer.name.upper() + ".")
print("My computer has " + str(my_computer.memory) + " kilobytes of volatile memory.")
my_computer.take_input()
my_computer.display_output()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment