Classes And Dictionaries¶
Facts Up-Front¶
class
is a statementCreates a class
Actually: a shorthand for creating a type
A class is callable
Creates an object (⟶
self
)Calls
__init__
on it (see Constructor)
Using Raw Dictionaries As Objects¶
Raw dictionary to hold attributes
person = {}
str
type keys as attributesperson['firstname'] = 'Joerg' person['lastname'] = 'Faschingbauer'
Attribute access is clumsy
person['firstname']
'Joerg'
The type of the object does not refect that it is a person
type(person)
dict
Much writing
Many opportunities for bugs/typos
⟶ BAD!
Enter Classes: An Empty Class, And Its Effects¶
Better notation for the same thing: class
Create empty class (one without class attributes and methods)
class Person: pass
Classes are first-class object ⟶ have a type
type(Person)
type
⟶ A-ha! Created a new type, obviously
Objects are instantiated by calling their type
person = Person() type(person)
__main__.Person
Attributes¶
Setting attributes
person.firstname = 'Joerg' person.lastname = 'Faschingbauer'
Getting attributes
person.firstname
'Joerg'
Unknown attribute access
person.svnr # <--- attribute 'svnr' does not exist
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[10], line 1 ----> 1 person.svnr # <--- attribute 'svnr' does not exist AttributeError: 'Person' object has no attribute 'svnr'
Summary: Classes Or Raw Dictionaries¶
Definitely less typing
Objects have type other than
dict
Classes are callable ⟶ creates instance of it (the object)
Dynamic Attribute Access¶
Attention
Do not overuse! (Except to save your job maybe)
hasattr()
getattr()
setattr()
dir()
obj.__dict__
class Person: pass person = Person() person.firstname = 'Joerg' person.lastname = 'Faschingbauer'
hasattr(person, 'firstname')
True
getattr(person, 'firstname')
'Joerg'
getattr(person, 'svnr')
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[14], line 1 ----> 1 getattr(person, 'svnr') AttributeError: 'Person' object has no attribute 'svnr'
setattr(person, 'svnr', '1037190666')
print('Boing, now having an ID', person.svnr)
Boing, now having an ID 1037190666