Home > Backend Development > Python Tutorial > Python中的super()方法使用简介

Python中的super()方法使用简介

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-10 15:08:03
Original
1469 people have browsed it

子类里访问父类的同名属性,而又不想直接引用父类的名字,因为说不定什么时候会去修改它,所以数据还是只保留一份的好。其实呢,还有更好的理由不去直接引用父类的名字,
这时候就该super()登场啦——

1

2

3

4

5

6

7

8

9

10

class A:

 def m(self):

  print('A')

 

class B(A):

 def m(self):

  print('B')

  super().m()

 

B().m()

Copy after login

当然 Python 2 里super() 是一定要参数的,所以得这么写:

1

2

3

4

class B(A):

 def m(self):

  print('B')

  super(B, self).m()

Copy after login

super在单继承中使用的例子:

1

2

3

4

5

6

7

8

9

class Foo():

  def __init__(self, frob, frotz)

    self.frobnicate = frob

    self.frotz = frotz

 

class Bar(Foo):

  def __init__(self, frob, frizzle)

    super().__init__(frob, 34)

    self.frazzle = frizzle

Copy after login

此例子适合python 3.x,如果要在python2.x下使用则需要稍作调整,如下代码示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

class Foo(object):

  def __init__(self, frob, frotz):

    self.frobnicate = frob

    self.frotz = frotz

 

class Bar(Foo):

  def __init__(self, frob, frizzle):

    super(Bar,self).__init__(frob,34)

    self.frazzle = frizzle

 

new = Bar("hello","world")

print new.frobnicate

print new.frazzle

print new.frotz

Copy after login

需要提到自己的名字。这个名字也是动态查找的,在这种情况下替换第三方库中的类会出问题。

`super()`` 很好地解决了访问父类中的方法的问题。

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template