class C1(object):
"C1 doc"
def f1(self):
# do something with self
def f2(self):
# do something with self
# create C1 instances
myc1 = C1()
myc1a = C1()
# call f2 method on one instance
myc1.f2()
class C1(object):
"C1 doc"
def f1(self):
# do something with self
def f2(self):
# do something with self
# create C1 instances
myc1 = C1()
myc1a = C1()
# call f2 method on one instance
myc1.f2()
>>> print(myc1.f1)
hello
>>> print(myc1.f2)
<bound method C1.f2 of <__main__.C1 object at 0x1401d6b50>>
>>> print(myc1.__doc__)
C1 doc
>>> myc1.f1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
instance.method(arguments...)
class.method(instance, arguments...)
>>> C1.count = 12
>>> print(C1.count)
12
>>> C1.f1
<unbound method C1.f1>
>>> C1.f1(myc1)
>>> print(C1.__doc__)
C1 doc
>>> C1.__doc__ = "new documentation"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: attribute '__doc__' of 'type' objects is not writable
>>> help(C1)
…
>>> class C1:
... count = 12
...
>>> myc1 = C1()
>>> print(myc1.count)
12
>>> myc1.count = 20
>>> print(myc1.count)
20
>>> print(C1.count)
12
class C1(object):
"C1 doc"
def f1(self):
# do something with self
def f2(self):
# do something with self
# create a C1 instance
myc1 = C1()
# call f2 method
myc1.f2()
class Stack(list):
"LIFO data structure"
def push(self, element):
self.append(element)
# Might also have used:
#push = list.append
st = Stack()
print("Push 12, then 1")
st.push(12)
st.push(1)
print("Stack content", st)
print("Popping last element", st.pop())
print("Stack content now", st)
list
class to implement a stack data structure.
(Superclasses may be either Python- or user-defined classes.)
Elements may be added to and removed from a stack
using push and pop operations, respectively.
The last element added by push
is the first to be removed by pop.class Stack(list):
push = list.append
class Calculator(Stack):
def __init__(self):
Stack.__init__(self)
self.accumulator = 0
def __str__(self):
return str(self.accumulator)
def push(self, value):
Stack.push(self, value)
self.accumulator = value
c = Calculator()
c.push(10)
print(c)
def what_is_this(data):
if isinstance(data, str):
# In Python 2, we would use basestring instead of str
return "instance of string"
elif hasattr(data, "__class__"):
return ("instance of %s" %
data.__class__.__name__)
raise TypeError("unknown type: %s" %
str(data))
class NC(object): pass
class OC: pass
print(what_is_this("Hello"))
print(what_is_this(12))
print(what_is_this([1, 2]))
print(what_is_this({12:14}))
print(what_is_this(NC()))
print(what_is_this(OC()))
def histogram(s):
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
print(histogram("aabc"))
print(histogram([1, 2, 2, 5]))
print(histogram(("abc", "abc", "xyz")))
class InfiniteSeries(object):
def next(self):
raise NotImplementedError("next")
class Fibonacci(InfiniteSeries):
def __init__(self):
self.n1, self.n2 = 1, 1
def next(self):
n = self.n1
self.n1, self.n2 = self.n2, self.n1 + self.n2
return n
class Geometric(InfiniteSeries):
def __init__(self, divisor=2.0):
self.n = 1.0 / divisor
self.nt = self.n / divisor
self.divisor = divisor
def next(self):
n = self.n
self.n += self.nt
self.nt /= self.divisor
return n
def print_series(s, n=10):
for i in range(n):
print("%.4g" % s.next(), end=' ')
print()
print_series(Fibonacci())
print_series(Geometric(3.0))
print_series(InfiniteSeries())
InfiniteSeries
defines the common interface (the __init__
and
next
methods).Fibonacci
and Geometric
overrode both methods so they have different behavior.print_series
function, must use s.next()
to call the method because it
does not know what class s
belongs to.
def tell_me_about(data):
print(str(data))
print(" Id:", id(data))
if isinstance(data, str):
# In Python 2, we would use basestring instead of str
print(" Type: instance of string")
elif hasattr(data, "__class__"):
print(" Type: instance of %s" % data.__class__.__name__)
else:
print(" Type: unknown type")
if hasattr(data, "__getitem__"):
like = []
if hasattr(data, "extend"):
like.append("list-like")
if hasattr(data, "keys"):
like.append("dict-like")
if like:
print(" %s" % ", ".join(like))
tell_me_about({12:14})
class NC(object): pass
nc = NC()
nc_copy = nc
tell_me_about(nc)
tell_me_about(nc_copy)
tell_me_about(NC())
{12: 14}
Id: 5370941216
Type: instance of dict
dict-like
<__main__.NC object at 0x1401d6410>
Id: 5370635280
Type: instance of NC
<__main__.NC object at 0x1401d6410>
Id: 5370635280
Type: instance of NC
<__main__.NC object at 0x1401d6490>
Id: 5370635408
Type: instance of NC
def list_attributes(obj):
for attr_name in dir(obj):
print(" %s:" % attr_name, end=' ')
value = getattr(obj, attr_name)
if callable(value):
print("function/method")
else:
print(value)
list_attributes(list)
__add__: function/method
__class__: function/method
__contains__: function/method
__delattr__: function/method
__delitem__: function/method
__delslice__: function/method
__doc__: list() -> new empty list
list(iterable) -> new list initialized from iterable's items
__eq__: function/method
__format__: function/method
__ge__: function/method
__getattribute__: function/method
__getitem__: function/method
__getslice__: function/method
__gt__: function/method
__hash__: None
__iadd__: function/method
__imul__: function/method
__init__: function/method
__iter__: function/method
__le__: function/method
__len__: function/method
__lt__: function/method
__mul__: function/method
__ne__: function/method
__new__: function/method
__reduce__: function/method
__reduce_ex__: function/method
__repr__: function/method
__reversed__: function/method
__rmul__: function/method
__setattr__: function/method
__setitem__: function/method
__setslice__: function/method
__sizeof__: function/method
__str__: function/method
__subclasshook__: function/method
append: function/method
count: function/method
extend: function/method
index: function/method
insert: function/method
pop: function/method
remove: function/method
reverse: function/method
sort: function/method
class Rectangle(object):
"""A rectangle class where dimensions
are kept in a sorted array."""
def __init__(self, w, h):
self._set_dims(w, h)
def _set_dims(self, w, h):
self.width = w
self.height = h
if w < h:
self.dim = [w, h]
else:
self.dim = [h, w]
def set_dims(self, w, h):
assert self._check_invariant()
self._set_dims(w, h)
assert self._check_invariant()
def set_width(self, w):
assert self._check_invariant()
self.width = w
assert self._check_invariant()
def smallest_dimension(self):
assert self._check_invariant()
return self.dim[0]
def _check_invariant(self):
if self.dim[0] > self.dim[1]:
return False
if self.width not in self.dim:
return False
if self.height not in self.dim:
return False
return True
r = Rectangle(10, 20)
print(r.smallest_dimension())
r.set_dims(15, 20)
print(r.smallest_dimension())
r.set_width(30)
print(r.smallest_dimension())
10
15
Traceback (most recent call last):
File "conditions.py", line 41, in
r.set_width(30)
File "conditions.py", line 35, in set_width
assert self._check_invariant()
AssertionError