1、类继承:子类继承父类的属性和方法,同时可以定制只属于自己的功能。
2、一般情况下,要重写类的构造器,然后再调用基类的构造器,不然基类的构造器不会自动调用。
例子:
class AddBook:
def __init__(self,name,phone):
self.name=name
self.phone=phone
def updateph(self,newph):
self.phone=newph
class EmplAddBook(AddBook):
def __init__(self,name,phone,uid,email):
AddBook.__init__(self,name,phone)
self.uid=uid
self.email=email
def updateEmail(self,newem):
self.email=newem
EmplAddBook类继承**dBook的属性,name\phone,方法updateph(),同时又自己新的属性uid,email和方法updateEmail.
3、类继承容易写错的地方:
class AddBook:
def __init__(self,name,phone):
self.name=name
self.phone=phone
def updateph(self,newph):
self.phone=newph
class EmplAddBook(AddBook):
def __init__(self,name,phone,uid,email):
AddBook.__init__(name,phone)
self.uid=uid
self.email=email
def updateEmail(self,newem):
self.email=newem
错误吗:
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
luo=EmplAddBook("luo","13555555555","123456","
luo@163.com")
File "C:/Python27/test/testclass1.py", line 28, in __init__
AddBook.__init__(name,phone)
TypeError: unbound method __init__() must be called with AddBook instance as first argument (got str instance instead)
错误的原因:
子类中调用基类构造器时,参数错误。