c++ & python modula-3
a basic class:
class ClassName: <statement-1> . . . <statement-N>it will generate a new namespace
class MyClass: "A simple example class" i = 12345 def f(self): return 'hello world'
x = MyClass()
initial
def __init__(self): self.data = []
>>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5)
realization object
1. data property
x.counter = 1 while x.counter < 10: x.counter = x.counter * 2 print x.counter del x.counter
2. cite property
objects are not the only owner of functions, class have the authority as well, and there is some things different between them still.
# Function defined outside the class def f1(self, x, y): return min(x, x+y) class C: f = f1 def g(self): return 'hello world' h = g
class Bag: def __init__(self): self.data = [] def add(self, x): self.data.append(x) def addtwice(self, x): self.add(x) self.add(x)
derived:
class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N>all function in python are virtual for c++ programer
class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N>
exception is a class as well
iterator
for element in [1, 2, 3]: print element for element in (1, 2, 3): print element for key in {'one':1, 'two':2}: print key for char in "123": print char for line in open("myfile.txt"): print line
>>> s = 'abc' >>> it = iter(s) >>> it <iterator object at 0x00A1DB50> >>> it.next() 'a' >>> it.next() 'b' >>> it.next() 'c' >>> it.next()
>>> class Reverse: "Iterator for looping over a sequence backwards" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] >>> for char in Reverse('spam'): print char
generator
>>> def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] >>> for char in reverse('golf'): print char