Lecture Notes 15#
classes#
a_string = "hello"
type(a_string)
str
a_string.upper()
'HELLO'
class Person:
count = 0
def __init__(self, given_name="X", surname="Y"):
self.given_name = given_name
self.surname = surname
Person.count += 1
def __str__(self):
return f"{self.surname}, {self.given_name}"
def __repr__(self):
return f'Person("{self.given_name}", "{self.surname}")'
def display_person(self):
print(f"My name is {self.surname}, {self.given_name} {self.surname}")
Person()
Person("X", "Y")
person = Person("Joe", "Smith") # starts by calling __init__(self, "Joe", "Smith")
dir(person)
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'count',
'display_person',
'given_name',
'surname']
person.__dict__
{'given_name': 'Joe', 'surname': 'Smith'}
person.given_name
'Joe'
person.surname
'Smith'
person.__str__()
'Smith, Joe'
str(person) # delegates logic to person.__str__
'Smith, Joe'
print(person)
Smith, Joe
person.given_name = "John"
print(person)
Smith, John
person.display_person()
My name is Smith, John Smith
Person.count
2
person.count
2
person2 = Person("Jane", "Doe")
print(person2)
Doe, Jane
Person.count
3
person2.count
3
person.count
3
person
Person("John", "Smith")
person.__repr__()
'Person("John", "Smith")'
repr(person) # delegates ro person.__repr__
'Person("John", "Smith")'
person.given_name
'John'
person.__dict__['given_name']
'John'
person.__getattribute__('given_name')
'John'
operator overloading#
1 + 2
3
"1" + "2"
'12'
[1] + [2]
[1, 2]
# + delegated to __add__ method
class MyComplex:
def __init__(self, re=0, im=0):
self.re = re
self.im = im
def __add__(self, other):
sum_re = self.re + other.re
sum_im = self.im + other.im
return MyComplex(sum_re, sum_im)
def __neg__(self):
return MyComplex(-self.re, -self.im)
def __repr__(self):
return f'MyComplex({self.re}, {self.im})'
def __str__(self):
if self.im >= 0:
return f'{self.re} + {self.im}i'
else:
return f'{self.re} - {-self.im}i'
#compare with int
int(), int('12'), int(12)
(0, 12, 12)
z = MyComplex()
z.re
0
z.im
0
z + z
MyComplex(0, 0)
z1 = MyComplex(1, 2)
z + z1
MyComplex(1, 2)
print(z1 + z1)
2 + 4i
z2 = MyComplex(1, -2)
z2
MyComplex(1, -2)
print(z2)
1 - 2i
print(z1 + z2)
2 + 0i
z1
MyComplex(1, 2)
-z1
MyComplex(-1, -2)
print(z1, -z1)
1 + 2i -1 - 2i