There is no difference between class attributes created in the class body, outside the body by assigning an attribute, or outside the body by explicitly binding an entry in C.__dict__.
When you call C(*args,**kwds) to create a new instance of class C, Python first calls C.__new__(C,*args,**kwds). Python uses __new__’s return value x as the newly created instance. Then, Python calls C._ _init_ _(x,*args,**kwds), but only when x is indeed an instance of C or any of its subclasses (otherwise, x’s state remains as __new__ had left it).
1
2
x = C.__new__(C, 23)
if isinstance(x, C): type(x).__init__(x, 23)
Decorators
1
2
3
4
5
6
7
deff(cls, ...):
...definition of f snipped...
f = classmethod(f)
#等价于@classmethoddeff(cls, ...):
...definition of f snipped...
# r.findall(s)import re
reword = re.compile(r'\w+') # reword = re.compile('(\w+)\s')for aword in reword.findall(open('afile.txt').read()): print aword
# r.finditer(s)# r.match(s,start=0,end=sys.maxint)import re
digs = re.compile(r'\d+')
for line in open('afile.txt'):
# to print all lines in a file that start with digitsif digs.match(line): print line,
# r.search(s,start=0,end=sys.maxint)import re
digs = re.compile(r'\d+')
for line in open('afile.txt'):
# to print all lines containing digitsif digs.search(line): print line,
# r.split(s,maxsplit=0)import re
rehello = re.compile(r'hello', re.IGNORECASE)
astring = ''.join(rehello.split(astring))
# r.sub(repl,s,count=0)import re
rehello = re.compile(r'hello', re.IGNORECASE)
astring = rehello.sub('', astring, 1)
# r.subn(repl,s,count=0)import re
rehello = re.compile(r'hello', re.IGNORECASE)
junk, count = rehello.subn('', astring)
print'Found', count, 'occurrences of "hello"'