Python初学之类的继承和多态

子类可以继承父类的公有成员,但是不可继承私有成员。

若在派生类中调用基类的方法,则super(teacher,self).__init__(name,age,sex),或者Person.__init__(self,name,age,sex).



 class Person(object):
	def __init__(self,name = '',age = 10,sex = 'man'):
		self.setName(name)
		self.setAge(age)
		self.setSex(sex)
	def setName(self,name):
		if not isinstance(name,str):
			print 'name must be string'
			return
		self.__name = name
	def setAge(self,age):
		if not isinstance(age,int):
			print' age must be integer'
			return
		self.__age = age
	def setSex(self,sex):
		if sex !=  'man' and sex != 'woman':
			print 'sex must be man or women'
		        return
	        self.__sex = sex
	def show(self):
		print 'name:',self.__name
		print 'age:',self.__age
		print 'sex:',self.__sex

		
>>> class Teacher(Person):
	def __init__(self,name = '',age = 30,sex = 'man',job= 'tutor'):
		Person.__init__(self,name,age,sex)
		self.setJob(job)
	def setJob(self,job):
		if not isinstance(job,str):
			print 'job must be string'
	                return
	        self.__job = job
	def show(self):
		Person.show(self)
		print'job:',self.__job

		
>>> xiaoming = Person('xiaoming',30,'man')
>>> xiaoming.show()
name: xiaoming
age: 30
sex: man
>>> xiaohong = Teacher('xiaohong',40,'woman','math teacher')
>>> xiaohong.show()
name: xiaohong
age: 40
sex: woman
job: math teacher




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值