Last active
March 25, 2017 20:05
-
-
Save keithweaver/b280873f713a13202b40ca385527c13e to your computer and use it in GitHub Desktop.
Example Objects within single file in Python
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 is an example of using Object/Classes in Python. | |
# The code has been tested with Python 2.7. | |
# My Car Object | |
class ExampleCarObject: | |
# This is the constructor so when creating the object, these are | |
# the required parameters. "self" is needed as the first parameter | |
# for all functions in the object but when call it, you do NOT | |
# pass anything in. At the bottom there is an example. | |
def __init__(self, carOwner): | |
# Uses the parameter carOwner to set the owner within this example | |
self.owner = carOwner | |
# The color of the car is blank for now | |
self.color = '' | |
# Can retrieve objects | |
# Example. c.getCarOwner() | |
def getCarOwner(self): | |
return self.owner | |
# Can also create addition functions (setters) | |
def setCarColor(self, color): | |
self.color = color | |
def getCarColor(self): | |
return self.color | |
def printCarInfo(self): | |
if self.color != '': | |
print (self.owner + ' owns a ' + self.color + ' car.') | |
else: | |
print (self.owner + ' owns a car.') | |
# Car 1 has a owner named john. This is an example of calling | |
# the constructor (__init__) | |
car1 = ExampleCarObject('John') | |
print ('Car 1 is owned by ' + car1.getCarOwner()) | |
# Set the car color | |
car1.setCarColor('blue') | |
print ('And there car is ' + car1.getCarColor()) | |
# Output so far is: | |
# Car 1 is owned by John | |
# And there car is blue | |
# Create second object | |
car2 = ExampleCarObject('Jane') | |
# Print info about both cars | |
car1.printCarInfo() | |
car2.printCarInfo() | |
# Additional output is: | |
# John owns a blue car. | |
# Jane owns a car. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment