Skip to content

py_object

amaskey edited this page Mar 25, 2018 · 1 revision

Python object

Datetime object

>>> from datetime import date
>>> date
<class 'datetime.date'>
>>> today = date(2017, 2, 23)
>>> today
datetime.date(2017, 2, 23)
>>> bday = date(2017, 5, 20)
>>> bday - today
datetime.timedelta(86)
>>> str(bday - today)
'86 days, 0:00:00'
>>> today.year
2017
>>> today.month
2
>>> today.strftime('%A %B %d')
'Thursday February 23'
>>> 

Objects

  • represents information
  • consist of data and behavior, bundled together to create abstractions
  • can represent things but also properties, interactions and processes
  • type of oject is called a class; classes are first class values in python
  • object oriented programming:
    • a metaphor for organizing large programs
    • special syngtax that can improve the composition of programs
  • in python, every value is an object
    • all objects have attributes
    • a ot og data manipulation happens through object methods
    • functions do one thing; objects do many related things

String object

>>> s = 'Hello'
>>> s.lower()
'hello'
>>> s.upper()
'HELLO'
>>> s.swapcase()
'hELLO'
>>> s
'Hello'
>>>

Unicode object

>>> from unicodedata import name, lookup
>>> name('A')
'LATIN CAPITAL LETTER A'
>>> lookup('WHITE SMILING FACE')
'☺'
>>> lookup('SNOWMAN')
'☃'
>>> lookup('SOCCER BALL')
'⚽'
>>> lookup('BABY')
'👶'
>>> lookup('BABY').encode()
b'\xf0\x9f\x91\xb6'
>>> 'A'.encode()
b'A'
>>> 

Object mutation

  • object can change its value over time
>>> suits = ['coin', 'string', 'myriad']
>>> original_suits = suits
>>> suits.pop()
'myriad'
>>> suits.remove('string')
>>> suits
['coin']
>>> suits.append('cup')
>>> suits.extend(['sword', 'club'])
>>> suits
['coin', 'cup', 'sword', 'club']
>>> suits[2] = 'spade'
>>> suits[0:2] = ['heart', 'diamond']
>>> suits
['heart', 'diamond', 'spade', 'club']
>>> original_suits
['heart', 'diamond', 'spade', 'club']
>>> 
  • first example of an object changing state --> mutation
  • the same object can change in value throughout the cource of computation

mutating dictionary

>>> numerals = {'I': 1, 'V': 5, 'X': 10}
>>> numerals
{'V': 5, 'X': 10, 'I': 1}
>>> numerals['X']
10
>>> numerals['X'] = 11
>>> numerals['X']
11
>>> numerals
{'V': 5, 'X': 11, 'I': 1}
>>> numerals['L'] = 50
>>> numerals['L']
50
>>> numerals.pop('X')
11
>>> numerals
{'V': 5, 'L': 50, 'I': 1}
>>> 

immutable tuples

>>> 3,4,5,6
(3, 4, 5, 6)
>>> (3,4,5,6)
(3, 4, 5, 6)
>>> ()
()
>>> tuple()
()
>>> tuple([3, 4, 5])
(3, 4, 5)
>>> (2,)
(2,)
>>> (2)
2
>>> (2,3) + (4,6)
(2, 3, 4, 6)
>>> 2 in (2,4)
True

#tuples can be used as disctionary keys
>>> {(1, 2): 3}
{(1, 2): 3}

# list cannot
>>> {[1, 2]: 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> 
  • protected from mutation --> some protection but not full (name change)
  • numbers and strings are immutable just like tuples
  • mutable --> list, dictionary
  • immutable sequence may contact mutable values
>>> s[0] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> s[0][0] = 4
>>> s
([4, 2], 3)
>>> 

Idententy vs equality

>>> [10] == [10]
True
>>> a = [10]
>>> b = [10]
>>> a ==b
True
>>> a is b
False
>>> c = b
>>> c is b
True
>>> a.extend([20, 30])
>>> c.extend([55, 66])
>>> a
[10, 20, 30]
>>> b
[10, 55, 66]
>>> c
[10, 55, 66]
>>> 

risk of mutable default arguments

  • a default argument value is part of a function value not generated by a call
>>> def f(s=[]):
...     s.append(5)
...     return len(s)
... 
>>> f()
1
>>> f()
2
>>> f()
3
>>> 

Function with behavior that varies over time

model a bank acount

  • balance

100

  • withdraw(25)

75

  • withdraw(25)

50

  • withdraw(60)

'insufficient funds'

  • balance is stored with the function
Clone this wiki locally