如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,实例如下
class Parent: # 定义父类 def myMethod(self): print ('调用父类方法') class Child(Parent): # 定义子类 def myMethod(self): print ('调用子类方法') c = Child() # 子类实例 c.myMethod() # 子类调用重写方法 super(Child,c).myMethod() #用子类对象调用父类已被覆盖的方法执行以上程序输出结果为
调用子类方法 调用父类方法
super() 函数是用于调用父类(超类)的一个方法
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。 MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
以下是 super() 方法的语法super(type[, object-or-type]) 参数 type – 类 object-or-type – 类,一般是 self
实例 class A: def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super().add(x) b = B() b.add(2) # 3 使用 super 函数的实例 #!/usr/bin/python # -*- coding: UTF-8 -*- class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print ('Parent') def bar(self,message): print ("%s from Parent" % message) class FooChild(FooParent): def __init__(self): # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象 super(FooChild,self).__init__() print ('Child') def bar(self,message): super(FooChild, self).bar(message) print ('Child bar fuction') print (self.parent) if __name__ == '__main__': fooChild = FooChild() fooChild.bar('HelloWorld')执行结果
Parent Child HelloWorld from Parent Child bar fuction I’m the parent.
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例。 self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定是用 self。
实例 类的私有属性实例如下 class JustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 def count(self): self.__secretCount += 1 self.publicCount += 1 print (self.__secretCount) counter = JustCounter() counter.count() counter.count() print (counter.publicCount) print (counter.__secretCount) # 报错,实例不能访问私有变量执行以上程序输出结果为
1 2 2 Traceback (most recent call last): File "test.py", line 16, in <module> print (counter.__secretCount) # 报错,实例不能访问私有变量 AttributeError: 'JustCounter' object has no attribute '__secretCount'类的私有方法实例如下
class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): print('name : ', self.name) print('url : ', self.__url) def __foo(self): # 私有方法 print('这是私有方法') def foo(self): # 公共方法 print('这是公共方法') self.__foo() Python3 中类的静态方法、普通方法、类方法静态方法: 用 @staticmethod 装饰的不带 self 参数的方法叫做静态方法,类的静态方法可以没有参数,可以直接使用类名调用。 普通方法: 默认有个self参数,且只能被对象调用。 类方法: 默认有个 cls 参数,可以被类和对象调用,需要加上 @classmethod 装饰器。
Python同样支持运算符重载,我们可以对类的专有方法进行重载,实例如下
class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print (v1 + v2)以上代码执行结果如下所示
Vector(7,8)
链接: https://www.runoob.com/python3/python3-class.html.
