如何调用父类';Python中的子类中的方法?
在Python中创建简单的对象层次结构时,我希望能够从派生类调用父类的方法。在Perl和Java中,有一个用于this()的关键字。在Perl中,我可以这样做:如何调用父类';Python中的子类中的方法?,python,class,oop,object,inheritance,Python,Class,Oop,Object,Inheritance,在Python中创建简单的对象层次结构时,我希望能够从派生类调用父类的方法。在Perl和Java中,有一个用于this()的关键字。在Perl中,我可以这样做: package Foo; sub frotz { return "Bamf"; } package Bar; @ISA = qw(Foo); sub frotz { my $str = SUPER::frotz(); return uc($str); } 在Python中,似乎必须从子类显式地命名父类。 在上
package Foo;
sub frotz {
return "Bamf";
}
package Bar;
@ISA = qw(Foo);
sub frotz {
my $str = SUPER::frotz();
return uc($str);
}
在Python中,似乎必须从子类显式地命名父类。
在上面的示例中,我必须执行类似于Foo::frotz()
的操作
这似乎不正确,因为这种行为使得很难建立深层层次结构。如果孩子们需要知道什么类定义了继承的方法,那么就会创建各种信息
这是python中的一个实际限制,还是我理解上的一个差距,还是两者兼而有之?使用函数:
Foo类(条形):
def baz(自身,参数):
返回super().baz(arg)
对于Python<3,您必须明确选择使用并使用:
Foo类(条形):
def baz(自身,参数):
返回super(Foo,self).baz(arg)
Python还有:
super(类型[,对象或类型])
返回一个代理对象,该对象将方法调用委托给类型为的父类或同级类。
这对于访问类中已重写的继承方法非常有用。
搜索顺序与getattr()使用的相同,只是跳过了类型本身
例如:
class A(object): # deriving from 'object' declares A as a 'new-style-class'
def foo(self):
print "foo"
class B(A):
def foo(self):
super(B, self).foo() # calls 'A.foo()'
myB = B()
myB.foo()
Python中也有一个super()。它有点不稳定,因为Python有新旧样式的类,但非常常用,例如在构造函数中:
class Foo(Bar):
def __init__(self):
super(Foo, self).__init__()
self.baz = 5
无论直接父类是自己定义的还是继承的,都可以
super
仅在适当支持多重继承时才需要(并且只有在每个类都正确使用它时,它才起作用)。一般来说,AnyClass。如果AnyClass
没有定义/覆盖它,那么无论什么
都将在AnyClass
的祖先中查找AnyClass
,这对于“调用父方法的子类”和任何其他事件都适用 这是一种更抽象的方法:
super(self.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
我建议使用类
像这样的
class A:
def __init__(self):
print "I am Class %s"%self.__class__.__name__
for parentClass in self.__class__.__bases__:
print " I am inherited from:",parentClass.__name__
#parentClass.foo(self) <- call parents function with self as first param
class B(A):pass
class C(B):pass
a,b,c = A(),B(),C()
A类:
定义初始化(自):
打印“我是类%s”%self.\u类\u.\u名称__
对于self.\u class.\u.\u基中的父类:
打印“我继承自:”,父类。\u名称__
#parentClass.foo(self)下面是一个使用super()的示例:
#New-style classes inherit from object, or from another new-style class
class Dog(object):
name = ''
moves = []
def __init__(self, name):
self.name = name
def moves_setup(self):
self.moves.append('walk')
self.moves.append('run')
def get_moves(self):
return self.moves
class Superdog(Dog):
#Let's try to append new fly ability to our Superdog
def moves_setup(self):
#Set default moves by calling method of parent class
super(Superdog, self).moves_setup()
self.moves.append('fly')
dog = Superdog('Freddy')
print dog.name # Freddy
dog.moves_setup()
print dog.get_moves() # ['walk', 'run', 'fly'].
#As you can see our Superdog has all moves defined in the base Dog class
python中还有一个super()
如何从子类方法调用超类方法的示例
class Dog(object):
name = ''
moves = []
def __init__(self, name):
self.name = name
def moves_setup(self,x):
self.moves.append('walk')
self.moves.append('run')
self.moves.append(x)
def get_moves(self):
return self.moves
class Superdog(Dog):
#Let's try to append new fly ability to our Superdog
def moves_setup(self):
#Set default moves by calling method of parent class
super().moves_setup("hello world")
self.moves.append('fly')
dog = Superdog('Freddy')
print (dog.name)
dog.moves_setup()
print (dog.get_moves())
这个示例与上面解释的示例类似。但是有一个区别,super没有任何参数传递给它。上面的代码在python 3.4版本中是可执行的 如果您不知道可能会得到多少个参数,并且希望将它们全部传递给孩子:
class Foo(bar)
def baz(self, arg, *args, **kwargs):
# ... Do your thing
return super(Foo, self).baz(arg, *args, **kwargs)
(From:)Python3具有不同且更简单的语法来调用父方法
如果Foo
类继承自Bar
,则从Bar。可以通过super()从Foo
调用\uuuuu init\uuuuu>:
在Python 2中,我在super()方面运气不太好。我使用了来自
这条线上的jimifiki。
然后,我给它添加了我自己的小改动,我认为这是可用性方面的一个改进(特别是如果你有很长的类名)
在一个模块中定义基类:
# myA.py
class A():
def foo( self ):
print "foo"
然后将该类作为父类导入另一个模块:
# myB.py
from myA import A as parent
class B( parent ):
def foo( self ):
parent.foo( self ) # calls 'A.foo()'
许多答案解释了如何从父级调用已在子级中重写的方法
然而
“如何从子类调用父类的方法?”
也可能仅仅意味着:
“如何调用继承的方法?”
您可以调用从父类继承的方法,就像调用子类的方法一样,只要它们没有被覆盖
e、 g.在python 3中:
class A():
def bar(self, string):
print("Hi, I'm bar, inherited from A"+string)
class B(A):
def baz(self):
self.bar(" - called by baz in B")
B().baz() # prints out "Hi, I'm bar, inherited from A - called by baz in B"
是的,这可能是相当明显的,但我觉得如果不指出这一点,人们可能会给这篇文章留下这样的印象:为了访问python中的继承方法,您必须跳过荒谬的障碍。尤其是在搜索“如何在Python中访问父类的方法”时,这个问题的评价很高,而OP是从Python新手的角度编写的
我发现:
有助于理解如何访问继承的方法。在本例中,cafec_param
是基类(父类),abc
是子类abc
调用基类中的AWC
方法
class a(object):
def my_hello(self):
print "hello ravi"
class b(a):
def my_hello(self):
super(b,self).my_hello()
print "hi"
obj = b()
obj.my_hello()
class cafec_param:
def __init__(self,precip,pe,awc,nmonths):
self.precip = precip
self.pe = pe
self.awc = awc
self.nmonths = nmonths
def AWC(self):
if self.awc<254:
Ss = self.awc
Su = 0
self.Ss=Ss
else:
Ss = 254; Su = self.awc-254
self.Ss=Ss + Su
AWC = Ss + Su
return self.Ss
def test(self):
return self.Ss
#return self.Ss*4
class abc(cafec_param):
def rr(self):
return self.AWC()
ee=cafec_param('re',34,56,2)
dd=abc('re',34,56,2)
print(dd.rr())
print(ee.AWC())
print(ee.test())
您不能也执行“return Bar.baz(self,arg)”吗?如果是这样的话,哪一个更好?是的,你可以,但是OP在询问如何在调用站点(在本例中为Bar)不显式命名超类的情况下实现它。super()对于多重继承来说很奇怪。它调用“下一个”类。这可能是父类,也可能是层次结构中其他地方出现的一些完全不相关的类。我使用Python2.x,执行此操作时得到“Error:must-be-type,not-classobj”。语法super(Foo,self)
是否适用于Python2.x?在Python3.x中,首选super()
是否正确?我认为父类的命名不是一个坏主意。当子类从多个父类继承时,它会有所帮助,因为您可以显式地命名父类。虽然命名类的选项不是一个坏主意,但强制命名肯定是一个坏主意。请注意Python 2和Python 3之间超级处理的变化。命名类不再是必需的(尽管可能仍然是一个好主意,至少有时是这样)。self.\uuuu class\uuuuuu与super不匹配,因为self始终是实例,它的类始终是实例的类。这意味着如果在一个类中使用super(self.\uuuuuuu class\uuuuuuu..并且该类是从中继承的,那么它将
class a(object):
def my_hello(self):
print "hello ravi"
class b(a):
def my_hello(self):
super(b,self).my_hello()
print "hi"
obj = b()
obj.my_hello()
class cafec_param:
def __init__(self,precip,pe,awc,nmonths):
self.precip = precip
self.pe = pe
self.awc = awc
self.nmonths = nmonths
def AWC(self):
if self.awc<254:
Ss = self.awc
Su = 0
self.Ss=Ss
else:
Ss = 254; Su = self.awc-254
self.Ss=Ss + Su
AWC = Ss + Su
return self.Ss
def test(self):
return self.Ss
#return self.Ss*4
class abc(cafec_param):
def rr(self):
return self.AWC()
ee=cafec_param('re',34,56,2)
dd=abc('re',34,56,2)
print(dd.rr())
print(ee.AWC())
print(ee.test())
56
56
56
class department:
campus_name="attock"
def printer(self):
print(self.campus_name)
class CS_dept(department):
def overr_CS(self):
department.printer(self)
print("i am child class1")
c=CS_dept()
c.overr_CS()