Лекция 2
- Информация о материале
- Дата публикации
Задание
l1=[1,2,3]
l2=[3,4]
операция плюс определена, а вот операции - нет. Давайте ее определим так, чтобы
l1 - l2 = [1,2] - общий элемент 3 исчез.
Подсказка: унаследуйтесь от class A(list)
Вспомогательный материал к лекции 2
1.
#!/usr/bin/env python
class Simple(object):
a = 0
def __init__(self, a):
print "when constructor starts a=%d" % self.a
self.a = a
def get_a(self):
return self.a
def set_a(self, new_a):
self.a = new_a
class DSimple(object):
def __del__(self):
print "Desctructor here"
if __name__ == "__main__":
print "Constructor examples"
s = Simple(10)
print "a=%d" % s.get_a()
s.set_a(15)
print "now a=%d" % s.get_a()
print "Destructor examples"
d = DSimple()
del d
2.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class A(object):
def __init__(self):
print u"Конструктор класса A"
def say_hello(self):
print u"Hello from %s" % self.__class__.__name__
def do_something(self, val):
print u"Сотворим какое-нибудь добро с %s в A" % val
class B(A):
def __init__(self):
print u"Конструктор класса B"
super(B, self).__init__()
def do_something(self, val):
super(B,self).do_something(val)
print u"Треш и угар с %s в B" % val
if __name__ == "__main__":
a = A()
print "-"*20
b = B()
print "-"*20
a.say_hello()
b.say_hello()
print "-"*20
b.do_something(None)
3.
#!/usr/bin/env python
class Cow(object):
height = 150
weight = 500
position = 0
def say_moo(self):
print "Mooo"
def walk(self):
position += 10
if __name__ == "__main__":
cow = Cow()
methods = [method for method in dir(cow) if callable(getattr(cow, method)) and
(not method.startswith('__'))]
print "\n".join(methods)
4.
#!/usr/bin/env python
class Counter(object):
def __init__(self, start=1, stop=10):
self.current = start
self.stop = stop
def __iter__(self):
return self
def next(self):
if self.current > self.stop:
raise StopIteration
self.current += 1
return self.current - 1
if __name__ == "__main__":
counter = Counter(3,18)
for c in counter: print c
5.
#!/usr/bin/env python
class A(object):
def __init__(self):
print u"Constructor A"
class B(object):
def __init__(self):
print u"Constructor B"
def __str__(self):
return "B!"
class C(A,B):
def __init__(self):
print u"Constructor C"
super(C, self).__init__()
if __name__ == "__main__":
c = C()
print c
6.
#!/usr/bin/env python
import sys
class Monkey(object):
def __init__(self, name='ChiChiChi'):
self.name = name
if __name__ == "__main__":
def eat(self, bananas=0):
if bananas < 1:
raise RuntimeError("Monkey died")
print "Monkey %s got %d bananas " % (self.name, bananas)
Monkey.eat = eat
m = Monkey("ChaChaCha")
m.eat(2)
m.say_hello = lambda: sys.stdout.write("Hello\n");
m.say_hello()
7.
#!/usr/bin/env python
class A(object):
pass
class B(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "B(a=%r,b=%r)" % (self.a, self.b)
def __str__(self):
return "I'm B"
def __eq__(self, other):
if self.a == other.a and self.b == other.b:
return True
return False
if __name__ == "__main__":
a = A()
print repr(a)
print str(a)
print "-" *20
b1 = B(10,20)
print "str(b1)= %s" % b1
b2 = eval(repr(b1))
print "b1=%r id=%r, b2=%r id=%r" % (b1, id(b1), b2, id(b2))
print "b1 == b2: %s" % (b1==b2)
b2.a = 11
print "b1 == b2: %s" % (b1==b2)
8.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class ControlledExecution(object):
def __enter__(self):
return "hehe"
def __exit__(self, type, value, traceback):
print "I' m exit method!"
if __name__ == "__main__":
with ControlledExecution() as a:
raise RuntimeError(u"Беда беда!")