Docsity

CS 1301 Homework Classes - Object Oriented Programming, Summaries of Computer Programming

Toggle sidebar
bg1
Declaring a class
# Classes and Instances in Python (5.1.2.0) and Declaring a Class (5.1.2.1)
# DeclaringaClass-2.py
# Define the class Name
class Name:
def __init__(self):
self.firstname = "[no first name]"
self.lastname = "[no last name]"
# Define the class Person
class Person:
# Create a new instance of Person
def __init__(self):
# Person's default values
self.name = Name()
self.eyecolor = "[no eye color]"
self.age = -1
A couple of things worth noting as you study this:
Name is a class used as an attribute inside Person — this is called composition, where one
object contains another.
self.name = Name() on line 12 creates a new Name instance as part of every Person object, so
each person has their own firstname and lastname .
Default values like "[no first name]" and -1 for age are placeholders, typically overridden
when you create specific instances.
pf3

Partial preview of the text

Download CS 1301 Homework Classes - Object Oriented Programming and more Summaries Computer Programming in PDF only on Docsity!

Declaring a class

Classes and Instances in Python (5.1.2.0) and Declaring a Class (5.1.2.1)

DeclaringaClass-2.py

Define the class Name

class Name: def init(self): self.firstname = "[no first name]" self.lastname = "[no last name]"

Define the class Person

class Person:

Create a new instance of Person

def init(self):

Person's default values

self.name = Name() self.eyecolor = "[no eye color]" self.age = - 1

A couple of things worth noting as you study this:

Name is a class used as an attribute inside Person — this is called composition , where one object contains another. self.name = Name() on line 12 creates a new Name instance as part of every Person object, so each person has their own firstname and lastname. Default values like "[no first name]" and -1 for age are placeholders, typically overridden when you create specific instances.

CreatingInstances-1.py

Define the class Person

class Person:

Create a new instance of Person

def init(self):

Person's default values

self.firstname = "[no first name]" self.lastname = "[no last name]" self.eyecolor = "[no eye color]" self.age = - 1

Create a new Person and assign it to myPerson

myPerson = Person()

Print myPerson's values

print(myPerson.firstname) print(myPerson.lastname) print(myPerson.eyecolor) print(myPerson.age)

## MORE COMPLICATED VERSION

CreatingInstances-3.py

Define the class Name

class Name: def init(self): self.firstname = "[no first name]" self.lastname = "[no last name]"

Define the class Person

class Person: def init(self): self.name = Name() self.eyecolor = "[no eye color]" self.age = - 1

Create a new Person and assign it to myPerson

myPerson = Person()