String
>>> str('Python')
'Python'
>>> repr('Python')
"'Python'"
If __str__ is not defined then str() uses repr()
class StrRepres1:
def __init__(self, num):
self.num = num
>>> ex1 = StrRepres1(5)
>>> print (ex1)
<__main__.StrRepres1 instance at 0x107f53a28>
class StrRepres3:
def __init__(self, num):
self.num = num
def __repr__(self):
return "Repr"+str(self.num)
def __str__(self):
return "Str"+str(self.num)
>>> ex3 = StrRepres3(5)
>>> print (ex3)
Str 5
class StrRepres2:
def __init__(self, num):
self.num = num
def __repr__(self):
return «Repr "+str(self.num)
>>> ex2 = StrRepres2(5)
>>> print (ex2)
Repr 5
class MyList:
storage = [1, 2, 3, 4, 5]
def __str__(self):
return str(self.storage)
def __getitem__(self, index):
if type(index) is int:
print ('Index ' + str(index))
return self.storage[index]
elif type(index) is slice:
print (str(index))
return self.storage[index]
else:
print ('TypeError')
def __setitem__(self, index, value):
if type(index) is int:
print ('Index ' + str(index))
self.storage[index] = value
elif type(index) is slice:
print (str(index))
self.storage[index] = value
else:
print ('TypeError')
>>> examp = MyList() # called func output of func output value
>>> examp[1] # __getitem__ Index 1 #2
>>> examp[-1] # __getitem__ Index -1 #5
>>> examp[1:3] # __getitem__ slice(1, 3, None) #[2, 3]
>>> examp[0:2] = [0, 0] # __setitem__ slice(0, 2, None) #[0, 0, 3, 4, 5]
>>> examp[‘a'] = -9 # __setitem__ TypeError #None
>>> st = MyString("Hello Python")
>>> st[6] = ’C’
>>> print (st)
Hello Cython
>>> print (’C’ in st)
True
>>> for letter in st: # call __getitem__ to get letter
>>> print (letter)
class PowTwo:
def __init__(self, max = 0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
Output
>>> a = PowTwo(4)
>>> i = iter(a)
>>> next(i) #1
>>> next(i) #2
>>> next(i) #4
>>> next(i) #8
>>> next(i) #16
>>> next(i)
Traceback (most recent call last):
…
StopIteration
Yes, Python allows to implement iterator object using __iter__, __next__
But!
- If you need to check containing of item - overload __contains__ to use in operator
- If you want to iterate your container - use more elegant way of automatically iterating: for loop
>>> for element in my_list:
... print(element)
for loop automatically use method __getitem__ in the range of the size of your container
the operands are of different types
__radd__ is only called if the left operand does not support the corresponding operation __add__ (in our case, built-in type (int) doesn’t support __add__ for user type)
__add__ method of built-in type returns NotImplemented value
If user type doesn’t support __radd__ - Python interpreter raises TypeError exception
behavior of __call__ method is similar to the closure
f1(word):
def f2():
print(‘hello ', word)
return f2
cb3 = f1('world')
cb3() #hello world
class ExampleAccess:
def __init__(self, number):
self.number = number # call __setattr__
def __setattr__(self, key, value):
if key == ‘number':
# ! use special func __dict__[key] for initialization to avoid recursion CRASH !
self.__dict__[key] = value * 2
else:
raise AttributeError()
>>> ex = ExampleAccess(2) #call __init__
>>> print (ex.number) #4
>>> ex.number = 3 #call __setattr__
>>> print (ex.number) #6
Overloaded operators in the base class are inherited.
Если не удалось найти и скачать презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:
Email: Нажмите что бы посмотреть