标签:
初始化实例属性:输入关键字信息attr=‘attr1’可以用kw.iteritems()
class Person(object): def __init__(self,name,gender,birth,**kw): self.name=name self.gender=gender self.birth=birth for k,v in kw.iteritems(): setattr(self,k,v) xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student') print xiaoming.name print xiaoming.job
class Person(object): def __init__(self, name, score): self.name=name self.__score=score p = Person('Bob', 59) print p.name print p.__score
定义类属性:直接绑定在类上的属性不需要创建实例,可以直接用类名访问(类属性和实例属性冲突:先寻找实例属性赋值或者引用然后再找类属性)
class Person(object): count = 0 def __init__(self,name): self.name=name Person.count=Person.count+1 p1 = Person('Bob') print Person.count p2 = Person('Alice') print Person.count p3 = Person('Tim') print Person.count
class Person(object): def __init__(self, name, score): self.name=name self.__score=score def get_grade(self): return self.__score p1 = Person('Bob', 90) p2 = Person('Alice', 65) p3 = Person('Tim', 48) print p1.get_grade() print p2.get_grade() print p3.get_grade()
import types def fn_get_grade(self): if self.score >= 80: return 'A' if self.score >= 60: return 'B' return 'C' class Person(object): def __init__(self, name, score): self.name = name self.score = score p1 = Person('Bob', 90) p1.get_grade = types.MethodType(fn_get_grade, p1, Person) #将fn_get_grade绑定到P1实例 print p1.get_grade() # => A p2 = Person('Alice', 65) print p2.get_grade() # ERROR: AttributeError: 'Person' object has no attribute 'get_grade' # 因为p2实例并没有绑定get_grade
class Person(object): __count = 0 @classmethod def how_many(ck): return ck.__count def __init__(self,name): self.name=name Person.__count=Person.__count+1 print Person.how_many() p1 = Person('Bob') print Person.how_many()
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/a353833082/article/details/46893809