1.类的__init__方法接收关键字参数
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
可以了解到设置属性的两种方式;
- self.name=name
- setattr(self,"name",name)
2.动态添加方法到实例上
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)
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
def __init__(self,name):
self.name = name
Person.__count += 1
@classmethod
def how_many(cls):
return cls.__count
print Person.how_many()
p1 = Person('Bob')
print Person.how_many()