Object

In Python, all data are objects.
- an object represents a value
- objects created behind the scene
- programmer does explicitly create objects
- even functions are objects

title = "Sound of Music"  # string object
year = 1965               # integer object
rating = 8.1              # float object

genres = ["biography",
          "drama",
          "family",
          "musical",
          "romance"]      # list object (of string objects)
Example Variable (Name) Object (Value)
x = 5 x the integer 5
y = 1.2 y the float 1.2
z = 'A' z the string 'A'
p = True p the boolean True
q = None q the None object
import math math the math module
def hi() hi the hi function

References

Important: Variables are not objects!

  • Each variable refers to an object in memory
  • Two variables might refer to the same object

Name binding
Or as our zyBook says, names are bound to objects

  • an object can have more than one name bound to it

  • a name is bound to exactly one object

  • xybooks

More on objects

  • 3 properties of an object
    • value, type, identity (memory address of object)
  • type() returns the type of an object
  • id() returns the memory location of an ojects

Checkpoint 1

  • copy into Thonny and execute the following:
def demo_objects(num):
    datapoint = num * 3 / 4
    colors = ["purple", "pink", "gold"]
    print(f"for datapoint:{type(datapoint)} {id(datapoint)}")
    print(f"for colors:{type(colors)} {id(colors)}")
    print(f"for datapoint:{type(num)} {id(num)}")
    
demo_objects(65)

Mutable and Immutable

  • some object types are mutable and some types are immutable
    • int is immutable
      • what?? means assignment statement generates a new object
    • list is mutable
  • start PythonTutor and in the bottom, middle drop down, select render all objects on the heap (Python/Java)
    • write a python program that makes assignments to integers and creats a list, then visualize

Checkpoint 2: Using PythonTutor

List exercise

x = [1, 2, 3]
y = [4, 5, 6]
z = y
y = x
x = z
  • without PythonTutor
    • What is the final value of x, y, and z?
    • How many list objects were created?
    • How many integer objects were created?
  • with PythonTutor, check your answers

Recall strings

  • strings are immutable
    • len()
    • [] for accessing a value
      • can we change a character of the string?

Containers

  • container is an object that "contains" (references) other objects
    • list: [1, 2, 3] brackets
    • tuple: (1, 2, 3) parentheses
    • set: {1, 2, 3} braces
    • dict: {"one": 1, "two": 2, "three": 3} braces + colons

Sequences

  • store multiple values ordered and efficient
  • the sequence types we are learning in this chapter
    • strings (not in this chapter, have already learned)
    • lists
    • tuples
  • operations on sequences:
    • in, +, []
  • useful functions
    • len(my_seq)
    • foundindex= my_seq.index(x)
      • search for first occurence of x
    • min_value = min(my_seq) and max_value = max(my_sequence)
    • my_seq.count(x)

List

  • container
    • group values together and contains references to other objects
    • elements can be different types
  • a list is a sequence
  • uses [], index starting at 0
  • element is a list item
  • mutable
    • nums[2] = 10
  • negative indexing
    • nums[-1] is the last item in the list
    • nums[-2] is the second to last item in the list
  • list methods: a method instructs an object to perform some action
  • functions: independent blocks of code that can be called from anywhere
    • you have been writing functions so far
  • methods:
    • append(v) -- adds value v to the end
    • pop(i) -- removes value at index i
    • remove(v) -- removes first element v
    • index(v) -- index of first element v
    • count(v)-- number of value v in list

Stop

  • activity

Checkpoint 3

Copy into Thonny and add code to count the number of items in the list. Also add code to execute this function.


def list_examples():
  values = list((23, "go", 85.3, "bananas"))
  print(len(values))
  values.append(34)
  print(len(values))

Assert statements

  • boolean expression that check if the statement is true of false
    • if true, execution continues
    • if false, execution is stopped and throws an error
    • used for debugging and while developing your code
def calculate_average(numbers):
    assert len(numbers) > 0, "List must not be empty"
    total = sum(numbers)
    average = total / len(numbers)
    return average

data = []
result = calculate_average(data)

Assert statement to test a function

# Assume the function must return a positive result
def calculate_average(numbers):
    total = sum(numbers)
    average = total/len(numbers)
    return average


assert calculate_average([1,2,3]) > 0, "Invalid list"
assert calculate_average([1,2,-4]) > 0, "Invalid list"

Tuples

  • container and sequence type like a list
  • BUT immutable
  • len(), indexing, and other sequence functions
  • use () to create
  • use [] to access a entry in the tuple
def tuple_examples():
    jmu_facts =("purple", "gold", 721, "CS")
    print(f'colors: {jmu_facts[0] + jmu_facts[1]}')
    if "CS" in jmu_facts:
        print("Perfect")

Named Tuples

  • programmer can define their own type
  • the new type has named attributes
from collections import namedtuple

def name_tuple_examples():
    # create the new type Person
    Person = namedtuple("Person", ['name', 'job', 'company', 'years'])
    # create objects of type Person
    me = Person('Sharon', 'Professor', 'JMU', 14)
    CS1 = Person('Sydney', 'Software Engineer', 'Verizon', 6)
    CS2 = Person('Kathryn', 'Software Engineer', 'Epic', '2')
    print(me)
    print(CS1)
    print(CS2)
    print(f'{me.name}, {CS1[0]}, {CS2.name}')
    print(type(me[3]), type(CS2[3]))

name_tuple_examples()

Sets

  • like math sets
  • sets are not sequences but a container
  • unordered, no index
  • set can contain different data types
  • no duplicate values of elements in the set
  • sets are mutable in that can add and remove items
  • len(setid) is the number of elements
  • some methods:
    • seta.add(value)
    • seta.remove(value)
    • item = seta.pop() #random value
    • seta.update(setb) #adds setb elements to seta

Sets

  • math set operations: all return a set
  • set_ex is an existing set
    • set_ex.intersection(...)
    • set_ex.union(...)
    • set_ex.difference(...)

Dictionary

  • type dict
  • maps keys to values
    • key:value pair
  • use {} and :
  • mutable
  • only index [] with key value
  • key must be of an immutable type
    • int, float, boolean or string
    • no duplicate keys
  • value can be any type
  • mapping type
    • uses key, pair association
caffeine_content_mg = {
    'Mr. Goodbar chocolate': 122,
    'Red Bull': 33,
    'Monster Hitman Sniper energy drink': 270,
    'Lipton Brisk iced tea - lemon flavor': 2,
    'dark chocolate coated coffee beans': 869,
    'Regular drip or percolated coffee': 60,
    'Buzz Bites Chocolate Chews': 1639
}
print(caffeine_content_mg)

Modify Dictionaries

caffeine_content = {
    'Mr. Goodbar chocolate': 122,
    'Red Bull': 33,
    'Monster Hitman Sniper energy drink': 270,
    'Lipton Brisk iced tea - lemon flavor': 2,
    'dark chocolate coated coffee beans': 869,
    'Regular drip or percolated coffee': 60,
    'Buzz Bites Chocolate Chews': 1639
}
print(caffeine_content)
# add
caffeine_content['double expresso'] = 120
# delete
del caffeine_content['Buzz Bites Chocolate Chews']
# modify
caffeine_content['Red Bull'] = 35
print(caffeine_content, len(caffeine_content))

Dictionary methods

all_keys= caffeine_content.keys()
print(all_keys)
all_values = caffeine_content.values()

Mixed up example

  • not very useful but shows how the types can vary
car = {
"brand": "Ford",
"model": "Mustang",
1 : 1964, 
2 : "2023"
}

x = car.keys()
print(x)


Membership

  • membership operators
    • in and not in
      • return True or False
    • can use with string, list, tuple, set and dictionary
name = "Sharon Simmons"
print(("S" in name))

# must use key
my_dict = {'A': 1, 'B': 2, 'C': 3}
print("Z" in my_dict)

#useful
50 in range(1, 50) # does not include 50

Identify

  • identify operators
    • is and is not
      • return True or False
    • checks if bound to the same object
      • usually by memory address
    • does NOT compare
  • try in pythontutor
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x 
print(x is z)
print(y is z)

Function returning multipe values

  • a bit more details
  • a function can ONLY return one value
    • package multiple values into a container
      • typically a tuple
    • return the one container
    • unpack the return values

Example of unpacking

def example(a, b):
	alist = [a,b]
	c = a + b
	return alist, c
c,d = example(100, 75)
  • Visual in pythonTutor
  • Watch for the tuple
  • Tuple is immutable
  • are c and d immutable?
    • why or why not?

Next Activity