class First():
def setdata(self,string):
self.name = string
def display(self):
print(self.name)
class Second(First):
def display(self):
print("Current value: %s" % self.name)
class Third(Second):
def __init__(self,value):
self.name = value
def __add__(self,other):
self.name = self.name + other # не создается новый объект
def __mul__(self,n):
self.name = self.name * n
class Fourth(Third):
def __add__(self,other):
return Fourth(self.name + other) # создается новый объект
def __mul__(self,n):
return Fourth(self.name * n)
a = First()
b = Second()
a.setdata('Dima')
b.setdata(12.5)
a.display()
b.display()
c = Third("abc")
c + 'def '
c * 2
c.display()
d = Fourth(67)
d = d + 9
d = d * 10
d.display()
см. Лутц «Изучаем Python» (стр. 579-589)
class Super:
def method(self):
print('in Super.method')
def delegate(self):
self.action()
class Inheritor(Super):
pass
class Replacer(Super):
def method(self):
print('in Replacer.method')
class Extender(Super):
def method(self):
print('starting Extender.method')
Super.method(self)
print('ending Extender.method')
class Provider(Super):
def action(self):
print('in Provider.action')
if __name__ == '__main__':
for klass in (Inheritor, Replacer, Extender):
print('\n' + klass.__name__ + '...')
klass().method() # здесь сразу создается объект () и у него вызывается метод
print('\nProvider...')
x = Provider()
x.delegate()
Результат:
Inheritor...
in Super.method
Replacer...
in Replacer.method
Extender...
starting Extender.method
in Super.method
ending Extender.method
Provider...
in Provider.action
Перегрузка операторов
class Number:
def __init__(self, start):
self.data = start
def __sub__(self, other):
return Number(self.data - other)
x = Number(5)
y = x - 2
print(y.data)
Реализация доступа по индексу
class Indexer:
def __init__(self, start):
self.data = start
def __getitem__(self, index):
return self.data[index]
x = Indexer([5,3,9])
print(x[0])
for i in x:
print(i)
for i in range(3):
print(x[i])
y = Indexer('bams')
print(y[3])
print('m' in y) # True
a,b,c,d = y
print(a,c)
print(list(y))
Класс-обертка для списков:
class MyList:
def __init__(self,start):
self.wrapped = []
for i in start:
self.wrapped.append(i)
def __add__(self,other):
lst = []
for i in other:
lst.append(i)
return MyList(self.wrapped + lst)
def __mul__(self,time):
return MyList(self.wrapped * time)
def __getitem__(self,offset):
return self.wrapped[offset]
def __len__(self):
return len(self.wrapped)
def __getslice__(self,low,high):
return MyList(self.wrapped[low:high])
def append(self,node):
self.wrapped.append(node)
def __getattr__(self,name):
return getattr(self.wrapped,name)
def __repr__(self):
return repr(self.wrapped)
if __name__ == '__main__':
x = MyList('abcdef')
print(x)
print(x[2])
print(x[1:])
x.append('B')
print(x + 'ghi')
print(x * 3)
x.sort()
print(x)
Результат:
['a', 'b', 'c', 'd', 'e', 'f']
c
['b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'B', 'g', 'h', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'B', 'a', 'b', 'c', 'd', 'e', 'f', 'B', 'a', 'b', 'c', 'd', 'e', 'f', 'B']
['B', 'a', 'b', 'c', 'd', 'e', 'f']
from mylist import MyList
class MyListSub(MyList):
calls = 0 # счетчик класса
def __init__(self,start):
self.adds = 0 # счетчик экземпляра
MyList.__init__(self,start)
def __add__(self,other):
MyListSub.calls += 1
self.adds += 1
return MyList.__add__(self,other)
def stats(self):
return self.calls, self.adds
if __name__ == '__main__':
x = MyListSub('abcdef')
y = MyListSub('zyxwvut')
print(x[2])
print(x[1:])
print(x + 'ghi')
print(x + 'lkj')
print(y + 'iop')
print(x.stats(), y.stats())
Результат:
c
['b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'l', 'k', 'j']
['z', 'y', 'x', 'w', 'v', 'u', 't', 'i', 'o', 'p']
(3, 2) (3, 1)
class Meta:
def __getattr__(self,name):
print('get', name)
def __setattr__(self,name,value):
print('set',name, value)
x = Meta()
x.app
x.color = 'blue'
Результат:
get app
set color blue