(1)类的继承
——需要用super(subclass,self).init(args)继承父类的属性。后面的init里的self不必传递,因为super()里意境传递多,会隐式传递过去。
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Teacher(Person):
def __init__(self, name, gender, course):
super(Teacher,self).__init__(name,gender)
self.course=course
t = Teacher('Alice', 'Female', 'English')
print t.name
print t.course
(2)验证某变量属于某类,可以用isinstance,以下是用“实例是否属于某类”,同样可以用作“某变量是否是str”等验证。
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Student(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
class Teacher(Person):
def __init__(self, name, gender, course):
super(Teacher, self).__init__(name, gender)
self.course = course
t = Teacher('Alice', 'Female', 'English')
print isinstance(t,Person)
print isinstance(t,Student)
print isinstance(t,Teacher)
print isinstance(t,object)
(3)多态。简单理解就是一个东西可以根据给的参数不同变现出不同结果。在这里,一般是指父类子类等都具有同一个方法(输出结果不同),此时,调用不同类的方法则结果不同。
——首先是因为调用实例方法的时候,不看类型,只看实例有没有这个方法,有就行,如下:
——其次,是不管是子类父类,调用时,一般是先找自己有无这个方法,如没有再向上继承的找。
import json
class Students(object):
def read(self):
return r'["Tim", "Bob", "Alice"]'
s = Students()
print json.load(s)
(4) 多重继承:
class Person(object):
pass
class Student(Person):
pass
class Teacher(Person):
pass
class SkillMixin(object):
pass
class BasketballMixin(SkillMixin):
def skill(self):
return 'basketball'
class FootballMixin(SkillMixin):
def skill(self):
return 'football'
class BStudent(Student,BasketballMixin):
pass
class FTeacher(Teacher,FootballMixin):
pass
s = BStudent()
print s.skill()
t = FTeacher()
print t.skill()
(5) 任意多参数,用**kw:
class Person(object):
def __init__(self, name, gender,**kw):
self.name=name
self.gender=gender
for k,v in kw.iteritems():
setattr(self,k,v)
p = Person('Bob', 'Male', age=18, course='Python')
print p.age
print p.course