一、Python中的类
1.类的创建:
(1) 类变量:在创建的类中会定义一些变量,我们把这些变量叫作类变量,类变量的值在这个类的所有实例之间是共享的,同时内部类或者外部类也能对这个变量的值进行访问。
(2) __init__():是类的初始化方法,我们在创建一个类的实例时就会调用一次这个方法。
(3) self :代表类的实例,在定义类的方法时是必须要有的,但是在调用时不必传入参数。
示例1:
class Student:
student_Count = 0
def __init__(self,name,age):
self.name = name
self.age = age
Student.student_Count += 1
def dis_student(self):
print("Student name:",self.name,"Student age:",self.age)
#创建对象
student1 = Student("TANG","20")
student2 = Student("WU","22")
student1.dis_student()
student2.dis_student()
print("Total Student:",Student.student_Count)
示例1输出结果:
Student name: TANG Student age: 20
Student name: WU Student age: 22
Total Student: 2
2.类的集成:
我们可以将继承理解为:定义一个类,通过继承获得另一个类的所有方法,被继承的类叫作父类,进行继承的类叫作子类,这样可以有效地解决代码的重用问题,在提升了代码的效率和利用率的基础上还增加了可扩展性。
不过需要注意的是,当一个类被继承时,这个类中的初始化方法是不会被自动调用的,所以我们需要在子类中重新定义类的初始化方法。
另外,我们在使用 Python 代码去调用某个方法时,默认会先在所在类中进行查找,如果没有找到,则判断所在的类是否为子类,若为子类,就继续到父类中查找。
示例2:如何创建和使用子类
class People():
def __init__ (self,name,age):
self.name= name
self.age= age
def dis_name(self):
print ("name is :", self.name)
def set_age(self, age):
self.age = age
def dis_age(self):
print ("age is: ", self.age)
class Student(People):
def __init__(self,name,age,school_name):
# People.__init__(self,name,age)
# super(Student,self).__init__(self,name,age,school_name)
self.name=name
self.age=age
self.school_name=school_name
def dis_student(self):
print("school name is:",self.school_name)
stu = Student("Wu","20","GLDZ")
stu.dis_student()#调用子类的方法
stu.dis_name()#调用父类的方法
stu.dis_age() #调用父类的方法
stu.set_age(22) #调用父类的方法
stu.dis_age() #调用父类的方法
示例2输出结果:
school name is: GLDZ
name is : Wu
age is: 20
age is: 22
示例3:
class People():
def __init__(self,name,age):
self.name = name
self.age = age
def dis_name(self):
print ("name is :", self.name)
def set_age(self, age):
self.age = age
def dis_age(self):
print ("age is: ", self.age)
class Student(People):
def __init__(self,name,age):
#super().__init__(self,restaurant_name,cuisine_type)
super().__init__(name,age)
self.school_name="abc"
def dis_student(self):
print("school name is:",self.school_name)
stu = Student("Wu","20")
stu.dis_name()
stu.dis_age()
stu.dis_student()
示例3输出结果:
name is : Wu
age is: 20
school name is: abc
示例4:
class Father(object):
def __init__(self, name):
self.name=name
print ( "name: %s" %( self.name) )
def getName(self):
return 'Father ' + self.name
class Son(Father):
def __init__(self, name,age):
print ( "hi" )
self.name = name
self.age = age
def getName(self):
return 'Son '+ self.name + " is " + self.age
if __name__=='__main__':
son=Son('runoob','20')
print ( son.getName() )
示例4结果:
hi
Son runoob is 20
3.类的重写:
在继承一个类后,父类中的很多方法也许就不能满足我们现有的需求了,这时我们就要对类进行重写。
示例1:对类中的内容进行重写。
#定义父类
class Parent:
def __init__(self):
pass
def print_info(self):
print("This is Parent.")
#定义子类
class Child(Parent):
def __init__(self):
pass
#重写父类的方法
def print_info(self):
print("This is Child.")
child = Child()
child.print_info()#This is Child.
示例1的输出结果:
This is Child.