[i]Learn· Classes
Odds and Ends
Sometimes it is useful to have a data type similar to the Pascal “record” or C
“struct”, bundling together a few named data items. The idiomatic approach
is to use dataclasses for this purpose:
from dataclasses import dataclass
@dataclass
class Employee:
name: str
dept: str
salary: int
>>> john = Employee('john', 'computer lab', 1000)
>>> john.dept
'computer lab'
>>> john.salary
1000
A piece of Python code that expects a particular abstract data type can often be
passed a class that emulates the methods of that data type instead. For
instance, if you have a function that formats some data from a file object, you
can define a class with methods read() and
readline() that get the
data from a string buffer instead, and pass it as an argument.
Instance method objects have attributes, too:
m.__self__ is the instance
object with the method m(), and m.__func__ is
the function object
corresponding to the method.
example 1 of 2
[>_]Terminal
Output appears here when you press Run.
$ ▌