Sunday, April 28, 2013

generator in python

class GeneratorDemoException(Exception):
    def __str__(self):
        return "GeneratorDemoException occured"

def generator_demo():
    ret_1 = yield "demo of generator:"
    print "ret_1=",ret_1
    ret_2 = yield "call me with send(arg) then I set ret_1 with arg"
    print "ret_2=",ret_2
   
    try:
        ret_3 = yield "call me with next() and I always set ret_2 as None"
    except GeneratorDemoException,e:
        ret_3 = "failed to yield"
    print "ret_3=",ret_3
   
generator = generator_demo()
print generator.next()
print generator.send("arg_to_set_ret1")
print generator.next()
try:
    ret_from_throw = generator.throw(GeneratorDemoException,"test finished")
except:
    pass
   

Thursday, April 25, 2013

__hash__ in python

__hash__() should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together the hash values for the components of the object that also play a part in comparison of objects

If a class defines mutable objects, it should not implement __hash__(), since hashable collection implementations require that a object's hash value is immutable
__hash__ may now be set to None to explicitly flag instances of a class as unhashable,此外,为了保证对象的哈希的唯一性,一般来说:
def __hash__(self):
    return id(self)

Tuesday, April 23, 2013

Coercion rules in python[summary]

if the left operand is an instance of a built-in type or a new-style class, and
the right operand is an instance of a proper subclass of that type or class and overrides the base’s __rop__()
method, the right operand’s __rop__() method is tried before the left operand’s __op__() method.

When an in-place operator (like ‘+=‘) is used, if the left operand implements __iop__(), it is invoked without
any coercion(convert is explicit and coerce is implicit, for exam, 1.0+2)

Rich comparisons (implemented by methods __eq__() and so on) never use coercion. Three-way comparison
(implemented by __cmp__()) does use coercion under the same conditions as other binary operations use it.

Sunday, April 21, 2013

TIC紧急医疗保险注意事项

违反省医疗计划的费用(比如整体疗法,物理疗法啥的,我也不太懂)不理赔,太扯,因为发生紧急医疗,用什么治疗方式,都是医院定的;

不紧急的医疗不理赔,比较扯,什么是紧急,有多少是紧急,这个由公司界定;

加拿大之外(包括回国)发生的事故不赔偿;

怀孕、流产、堕胎、并发症不理赔;

紧急医疗之后的回访医疗(Follow-up visits) 最高被赔偿$5,000




发生紧急事故,必须24小时通知TIC;手术之前必须通知TIC

如果病人要求回国治疗,因此而发生的一切费用由TIC承担,但是病人一旦被遣返,TIC一般不再承担医疗费用(除非之前经过TIC允许)



Saturday, April 20, 2013

__metaclass__ in python

# __metaclass__ in python
print """to understand __metaclass__, you must know the following true:
Everything is an object.
'class' and 'type' are synonyms.
there is a special class named "type"
a class is an object and it's an instance of its metaclass type
a class's __metaclass__ can be set to metaclass type, which is subtype of type
`print type(int)` will print `type 'type'`
"""
class LonelyBear(object):
    class MetaBear(type): #a subclass of type
        def __new__(meta, name, bases, attrs):
            # do stuff...
            return type.__new__(meta, name, bases, attrs)
    __metaclass__ = MetaBear
print    type(LonelyBear)

__get__ in python

#__get__ in python
import math

class Square(object):
    class Area(object):
        def __get__(self, aBear, clsBear):
            if aBear is None:raise AttributeError
            return aBear.edge_length * aBear.edge_length
           
        def __set__(self, aBear, area):
            if aBear is None:raise AttributeError
            aBear.edge_length = math.sqrt(area)
    area = Area()
   
    def __init__(self,edge_length):
        self.edge_length = edge_length

aSquare = Square(3.0)
print aSquare.area
print Square.__dict__["area"].__get__(aSquare,Square)

aSquare.area = 16.0
print aSquare.edge_length

__dict__ in python

#__dict__ in python

class LonelyBear(object):
    class_attr01 = "default user defined class attr"
    def user_defined_func_or_mtd(self):
        pass

#<type 'dictproxy'>
print type(LonelyBear.__dict__)

#when visit class attr, you can use either class_name.__dict__[attr_name] or class_name.attr_name
if id(LonelyBear.__dict__["class_attr01"]) == id(LonelyBear.class_attr01):
    print "when visit class attr, you can use either class_name.__dict__[attr_name] or class_name.attr_name"

#class_name.__dict__[func_or_mtd_name] is <function user_defined_func_or_mtd at 0x026F4670>
#class_name.func_or_mtd_name is <unbound method LonelyBear.user_defined_func_or_mtd>
func_managed_by_dictproxy = LonelyBear.__dict__["user_defined_func_or_mtd"]
method_managed_by_cls_ns = LonelyBear.user_defined_func_or_mtd
if func_managed_by_dictproxy != method_managed_by_cls_ns:
    print "class_name.__dict__[func_or_mtd_name] is", func_managed_by_dictproxy
    print "class_name.func_or_mtd_name is", method_managed_by_cls_ns

lb = LonelyBear()
an_inst_without_instance_attr = lb.__dict__
#<type 'dict'> {}
print type(an_inst_without_instance_attr), an_inst_without_instance_attr
print """an attr is searched first from instance(inst_name.user_defined_inst_attr, if avaible), then class(cls_name.user_defined_cls_attr),
then the internal(you can use dir(inst_name) to view any possible attr)[note: I am not considering __getattr__ and other hooks]"""

#AttributeError: 'str' object has no attribute '__dict__'
print "some internal type has no __dict__ attr".__dict__

__getattribute__ in python

class shape(object):
    pass
   
class square(shape):
    def __init__(self,side):
        self.side = side
       
    def __getattribute__(self,name):
        if name != "area":return shape.__getattribute__(self,name)
        return self.side*self.side

aSquare = square(5)
print aSquare.side
print aSquare.area

Wednesday, April 17, 2013

__new__ in python

"""
<class '__main__.cchild'> False
True
<class '__main__.cchild'> True
a_base_attr a_child_attr
"""
class cbase(object):
    def __new__(cls):
        #cls is a class, not instance
        print cls,isinstance(cls,cbase)
        #create an instance of sup, and bound cls to it         
        sup=super(cbase, cls)       
        print isinstance(sup,super)
        #now sup know how to create instance of cbase       
        inst_of_cbase = sup.__new__(cls)
        print type(inst_of_cbase),isinstance(inst_of_cbase,cbase)
        #
        return inst_of_cbase
    def __init__(self,base_attr):
        self.base_attr=base_attr

class cchild(cbase):
    def __new__(cls,base_attr,child_attr):
        #before new inst of cchild, new inst of  all of its ancestors   
        return super(cchild, cls).__new__(cchild)
       
    def __init__(self,base_attr,child_attr):
        #explicitly call ancestors's __init__
        cbase.__init__(self,base_attr)
        self.child_attr=child_attr
       
aChild=cchild("a_base_attr","a_child_attr")
print aChild.base_attr,aChild.child_attr

Tuesday, April 16, 2013

[转]博客如何选择广告联盟

一、起付金额越低越好
二、支付方式越方便越好:国内以支持支付宝支付为最优选择,国外以支持paypal支付为最优选择
三、支付周期越短越好:一般而言,广告联盟都是月付,但也有一些是周付,甚至日付的
*四、推荐广告比点击广告更适合博客:因为对于推荐广告而言,文章的内容本身就是广告
*五、注意广告联盟的服务费用/扣量
六、根据自己的网站主题,谨慎地选择一些广告联盟来长久地做:多做做试验,直到找到最适合自己博客的广告联盟为止