9. Class
Class class (type) (instance) class (attribute)Class class method
Python class class C++ Modula-3 class Python class (Object Oriented Programming) class base class derived class (override) base class method method base class methodclass Python (runtime)
C++ class Modula-3 Python method method (explicit) (implicitly) Smalltak class import C++ Modula-3Pyhon base class (extension) C++ class
class Smalltalk C++ Modula-3 C++ Python
9.1.
(individuality) (scope) (aliasing) Python tuple listdictionary Python (pointer) (caller) Pascal
9.2. Python (Scope) (Namespace)
class Python Class definition Python
Python dictionary abs() (global) (local) maximize (prefix)
(attribute) (dot) z.realreal z modname.funcname modname funcname [1]
modname.the_answer = 42 del del modname.the_answer modname the_answer
Python (top-level invocation) __main__ builtins
(recursive invocation)
Python (textual region) (unqualified reference)
3 4
(enclosing function) (non-local) (non-global)
nonlocal nonlocal
Class definition
(run time) (compile time) (static name resolution) (dynamic name resolution)
Python global nonlocal (assignment) del x x import
9.2.1.
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
scope_test spam nonlocal scope_test spam global
global spam
9.3. class
Class
9.3.1. Class definition
Class definition
class ClassName:
<statement-1>
.
.
.
<statement-N>
Class definitiondef class definition if
class definition Class method
class definition
class definition class (wrapper) class definition class class definition class class definition class ClassName
9.3.2. Class
Class (attribute reference) (instantiation)
Python obj.name class class class definition
class MyClass:
""""""
i = 12345
def f(self):
return 'hello world'
MyClass.i MyClass.f Class (assign) MyClass.i __doc__ class (docstring)"A simple example class"
Class (function notation) class class class
x = MyClass()
class x
class class class __init__() method
def __init__(self):
self.data = []
class __init__() methodclass class __init__()
x = MyClass()
__init__() method class __init__()
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
9.3.3.
(data attribute) method
Smalltalk C++ x MyClass 16
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter
(method)""
method class class methodx.f method MyClass.f x.i MyClass.i x.f MyClass.f method
9.3.4. Method
method
x.f()
x = MyClass() 'hello world' methodx.f method
xf = x.f
while True:
print(xf())
hello world
method x.f() f() Python ...
method x.f() MyClass.f(x) n method (argument list) method
class class
9.3.5. Class
class class method
class Dog:
kind = 'canine' #
def __init__(self, name):
self.name = name #
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # Dog
'canine'
>>> e.kind # Dog
'canine'
>>> d.name # d
'Fido'
>>> e.name # e
'Buddy'
mutable list dictionary tricks list class list Dog
class Dog:
tricks = [] #
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks # dog
['roll over', 'play dead']
class
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # dog list
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']
9.4.
class
>>> class Warehouse:
... purpose = 'storage'
... region = 'west'
...
>>> w1 = Warehouse()
>>> print(w1.purpose, w1.region)
storage west
>>> w2 = Warehouse()
>>> w2.region = 'east'
>>> print(w2.purpose, w2.region)
storage east
method class Python C Python C Python
method method
method method method method
selfself Python Python class (browser)
class class method class definition class
#
def f1(self, x, y):
return min(x, x+y)
class C:
f = f1
def g(self):
return 'hello world'
h = g
fg h class C class C method h g
Method self method method
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
Method method class method import method class method class method class
class type object.__class__
9.5. (Inheritance)
class class derived class
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
BaseClassName derived class base class base class
class DerivedClassName(modname.BaseClassName):
derived class base class class base class class base class base class class
derived class DerivedClassName() class Method class base class method
Derived class base class method method method base class method base class method derived class method C++ Python method virtual
derived class method base class method base class method BaseClassName.methodname(self, arguments) base class BaseClassName
Python
isinstance()isinstance(obj, int)obj.__class__intintTrueissubclass()classissubclass(bool, int)Trueboolintsubclassissubclass(float, int)Falsefloatintsubclass
9.5.1.
Python base class class definition
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
parent class class DerivedClassName Base1 Base1 base class Base2
method super() (call-next-method) super call
parent class class class object object base class (linearize) class parent (monotonic) class subclassed parent class Python 2.3
In some cases multiple inheritance is not allowed; see Multiple inheritance for details.
9.6.
(private) Python Python _spam API (non-public)
class subclass name mangling __spam (identifier) _classname__spam classname class class
subclass method class method
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update # update()
class MappingSubclass(Mapping):
def update(self, keys, values):
# update()
# __init__()
for item in zip(keys, values):
self.items_list.append(item)
MappingSubclass __update Mapping class _Mapping__update MappingSubclass class _MappingSubclass__update
(debugger)
exec() eval() class class global (byte-compiled) getattr()setattr() delattr() __dict__
9.7.
Pascal record C struct dataclasses
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
Python class class method read() readline() method class
method m.__self__ method m() m.__func__ method
9.8. (Iterator)
(container) for
for element in [1, 2, 3]:
print(element)
for element in (1, 2, 3):
print(element)
for key in {'one':1, 'two':2}:
print(key)
for char in "123":
print(char)
for line in open("myfile.txt"):
print(line, end='')
Python for iter() __next__() method method __next__() StopIteration for next() __next__() method
>>> s = 'abc'
>>> it = iter(s)
>>> it
<str_iterator object at 0x10c90e650>
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
next(it)
StopIteration
class __iter__() method __next__() method class __next__() __iter__() self
class Reverse:
""""""
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
... print(char)
...
m
a
p
s
9.9. (Generator)
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
>>> for char in reverse('golf'):
... print(char)
...
f
l
o
g
class __iter__() __next__() method
self.index self.data
method StopIteration
9.10.
list comprehension (enclosing function) list comprehension
>>> sum(i*i for i in range(10)) # sum of squares
285
>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec)) # dot product
260
>>> unique_words = set(word for line in page for word in line.split())
>>> valedictorian = max((student.gpa, student.name) for student in graduates)
>>> data = 'golf'
>>> list(data[i] for i in range(len(data)-1, -1, -1))
['f', 'l', 'o', 'g']
>>> x = [[1,2,3], [], [4, 5]]
>>> g = (*i for i in x)
>>> list(g)
[1, 2, 3, 4, 5]
In most cases, generator expressions must be wrapped in parentheses. As a
special case, however, when provided as the sole argument to a function (as in
the examples involving sum, set, max, and list above), the
generator expression does not need to be wrapped in an additional set of
parentheses. That is to say, the following two pieces of code are semantically
equivalent:
>>> f(x for x in y)
>>> f((x for x in y))
as are the following:
>>> f(*x for x in y)
>>> f((*x for x in y))
__dict__ dictionary__dict__ (post-mortem debugger)