1.
Generators
def simpleGen():
yield 1
yield '2--->punch!'
myG = simpleGen()
'''
myG.next()
myG.next()
myG.next() #Exception
'''
for eachItem in simpleGen():
print eachItem,
print '-----------------------------------------'
from random import randrange
def randGen(aList):
while len(aList) > 0:
yield aList.pop(randrange(len(aList)))# Just like list.pop() and random.choice()
for item in randGen(['rock', 'paper', 'scissors']):
print item
2.
import longmodulename
short = longmodulename
del longmodulename
from cgi import FieldStorage as form
3.
globals().keys()
locals().keys()
4.
__del__
#!/usr/bin/env python
class AddressBookEntry(object):
'address book entry class'
def __init__(self, nm, ph):
self.name = nm
self.phone = ph
print 'Created instance for:', self.name
def updatePhone(self, newph):
self.phone = newph
print 'Updated phone# for:', self.name
def __del__(self):
#self.__class__.oobject.__del__(self)
print '__del__ from AddressBookEntry triggered'
class EmplAddressBookEntry(AddressBookEntry):
addressBookEntry = AddressBookEntry #take attention this
def __init__(self, nm, ph, id, em):
AddressBookEntry.__init__(self, nm, ph) #Call the parent init function
self.empid = id
self.email = em
def updateEmail(self, newem):
self.email = newem
print 'Updated e-mail address for:',self.name
def __del__(self):
self.__class__.addressBookEntry.__del__(self) #take attention this,
print '__del__ from EmplAddressBookEntry trigged'
if __name__ == '__main__':
john = EmplAddressBookEntry('Leslie', '123455', 27, 'john@spam.doe')
print john
print john.name
print john.email
5.
@staticmethod
@classmethod
#!/usr/bin/env python
"Note some important points here"
class TestStaticMethod:
@staticmethod
def foo():
print 'Calling static method foo()'
class TestClassMethod:
@classmethod
def foo(cls):
print 'calling class method foo()'
print 'foo() is part of class',cls.__name__
tsm = TestStaticMethod()
TestStaticMethod.foo()
tsm.foo()
tcm = TestClassMethod()
TestClassMethod.foo()
tcm.foo()
6.
super
# super here
class P(object):
def foo(self):
print "Hi, I am P-foo()"
class C(P):
def foo(self):
super(C, self).foo() #Call the base class foo()
print 'Hi, I am C-foo()'
c = C()
c.foo()
7.
ljust
print '-------------------------SortedKeyDict(dict)----------------------------'
class SortedKeyDict(dict):
def keys(self):
return sorted(super(SortedKeyDict, self).keys())
d = SortedKeyDict((('zheng-cai', 7), ('leslie', 27)))
print 'By iterator:'.ljust(15,' '),[key for key in d]
8.
MRO (Method Resolution Order)
print '----------------MRO-----------------------'
class B:
pass
class C:
def __init__(self):
print 'the default constructor'
class D(B, C):
pass
d = D() #the default constructor
----------------------------------------
class B(object):
pass
class C(object):
def __init__(self):
print 'the default constructor from new'
class D(B, C):
pass
d = D() #the default constructor from new