COMP1531

3.1 - Python - Objects

 

What are objects?

Objects

  • Technically, a fairly simple idea
  • Conceptually, a rich area of software design with complicated outcomes
  • There's a whole course on Object-Oriented Design and Programming, so we'll only focus on basic stuff here

 

Python is not an Object-Oriented language. It's a scripting language with class capabilities.

A simple example

from datetime import date

today = date(2019, 9, 26)

# 'date' is its own type
print(type(today))

# Attributes of 'today'
print(today.year)
print(today.month)
print(today.day)

# Methods of 'today'
print(today.weekday())
print(today.ctime())

obj.py

Objects in python

  • Contain attributes and methods
  • Attributes are values inside objects
  • Methods are functions inside objects
  • Methods can read or modify attributes of the object

Everything* is an object

  • Almost all values in python are objects
  • For example:
    • lists have an append() method

       

 

    • strings have a capitalize() method
animals = ["dog", "cat", "chicken"]
animals.append("sheep") # Modifies the list 'animals'
greeting = "hi there!"
print(greeting.capitalize()) # Returns a new string

Creating objects

  • Classes are blueprints for objects
class Student:
    def __init__(self, zid, name):
        self.zid = zid
        self.name = name
        self.year = 1
        
    def advance_year(self):
        self.year += 1
        
    def email_address(self):
        return self.zid + "@unsw.edu.au"
        
rob = Student("z3254687", "Robert Leonard Clifton-Everest")
hayden = Student("z3418003", "Hayden Smith")

student.py

Details

  • Methods can be invoked in different ways
    • rob.advance_year()
    • Student.advance_year(rob)
  • The 'self' argument is implicitly assigned the object on which the method is being invoked
  • The '__init__()' method is implicitly called when the class is constructed

Managing Data Example

Activity: Use the data in https://www.cse.unsw.edu.au/~cs1531/20T3/weatherAUS.csv to write a python program to determine the location with the most rain over the last years

Extra Help

Made with Slides.com