知行编程网知行编程网  2023-01-04 06:00 知行编程网 隐藏边栏  0 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python中有重写么的相关知识,包括python static,以及python重复值这些编程知识,希望对大家有参考作用。

python中有重写吗

继承父类方法

子类可以直接调用父类的方法

class Person():
	def __init__(self):
		pass			
	def hello(self):
		print 'hello'		
class Student(Person):
	def __init__(self):
		pass				
s = Student()
s.hello()				# hello

继承父类属性

这里需要注意的是,如果要继承父类的属性,必须在子类的构造函数中调用父类的构造函数,否则会报错,无法访问,因为父类没有被调用,构造函数中的属性自然是没有声明的

这时候如果调用父类的属性会报错,报错内容为Student实例没有name属性

# coding=utf-8

class Person():
	def __init__(self):
		self.name = '小明'
		self.age = 18	
		print('Person class init completed')		
	def hello(self):
		print 'hello'
class Student(Person):
	def __init__(self):
		print ('Student class init completed')		
s = Student()
print s.name

# Student class init completed
# Traceback (most recent call last):
#   File ".\classDemo.py", line 23, in <module>
#     print s.name
# AttributeError: Student instance has no attribute 'name'

下面是子类在构造函数中调用父类构造函数的情况,子类实例可以访问父类的属性

# coding=utf-8

class Person():
	def __init__(self):
		self.name = u'小明'
		self.age = 18		
		print('Person class init completed')			
	def hello(self):
		print 'hello'		
class Student(Person):
	def __init__(self):
		Person.__init__(self)		
		print ('Student class init completed')				
s = Student()
print s.name

# Person class init completed
# Student class init completed
# 小明

方法重写

有时当父类提供的方法不能满足要求时,可以在子类中重写父类的方法

在父类Person中,构造函数只定义了name和age这两个属性,print_into()函数也只打印了name和age这两个属性

在子类学生中,有一个额外的学校属性。显然,父类提供的功能是不够的。这时候子类就需要重写父类的方法来扩展父类的功能。

# coding=utf-8

class Person(object):
	def __init__(self, name, age):
		self.name = name
		self.age = age			
	def print_info(self):
		print 'name: ', self.name
		print 'age: ', self.age		
class Student(Person):
	def __init__(self, name, age, school):
		Person.__init__(self, name, age)		
		self.school = school		
	def print_info(self):
		super(Student, self).print_info()
        # python3 中可直接使用super()
        # Python2 一般为super(class, self), 且class要为新类
        # 新类就是由内置类型派生出来的类
		print 'school: ', self.school				
s = Student(u'小明', 18, u'家里蹲大学')
s.print_info()
	
# name:  小明
# age:  18
# school:  家里蹲大学

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享