python Iterator Custom Class Concrete Method
- 2021-10-13 08:10:04
- OfStack
1. Description
Iterators also have the ability to iterate over user-customized categories. Iteration objects need to support two ways: _iter__ (), which returns the iteration itself, and next (), which returns the next element.
2. Examples
class example(object):
def __init__(self,num):
self.num=num
def __iter__(self):
return self
def __next__(self):
if self.num <= 0:
raise StopIteration
tmp = self.num
self.num -= 1
return tmp
a = example(3)
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
Knowledge point expansion
python Custom Classes and Methods Used
class Person:
def __init__(self, first, middle, last, age):
self.first = first;
self.middle = middle;
self.last = last;
self.age = age;
def __str__(self):
return self.first + ' ' + self.middle + ' ' + self.last + \
' ' + str(self.age)
def initials(self):
return self.first[0] + self.middle[0] + self.last[0]
def changeAge(self, val):
self.age += val
myPerson = Person('Raja', 'I', 'Kumar', 21)
print(myPerson)
myPerson.changeAge(5)
print(myPerson)
print(myPerson.initials())
The running results are as follows:
Raja I Kumar 21
Raja I Kumar 26
RIK