Python 2.7 在Python中使用继承时跳过方法

Python 2.7 在Python中使用继承时跳过方法,python-2.7,inheritance,Python 2.7,Inheritance,第二类继承自第一类。所以在第一类中定义的所有方法都应该在第二类中可用。这两个类都有相同的方法,但参数不同。这里,函数method1是通过将字符串作为参数传递来调用的 class firstclass(): def method1(self,somestring): # method1 which has a string as a parameter print("method1 is invoked") class secondclass(firstclass):

第二类继承自第一类。所以在第一类中定义的所有方法都应该在第二类中可用。这两个类都有相同的方法,但参数不同。这里,函数method1是通过将字符串作为参数传递来调用的

class firstclass():
   def method1(self,somestring):     # method1 which has a string as a parameter
      print("method1 is invoked") 

class secondclass(firstclass):       # Secondclass inherits firstclass
   def method1(self):                # method1 of second class which has no parameters
      print("method2 is invoked")

def main():
   a=firstclass()      # creates object for the first class
   b=secondclass()     # creates object for the second class 
   b.method1("abc")    # which method will it call ???

main()

当使用secondclass的对象调用函数method1时,为什么不打印“method1已调用”

当您在
secondclass
中定义
method1
时,将覆盖从
firstclass
继承的方法。这意味着
secondclass
中的方法
method1
是您在该类中定义的方法,而不是继承的方法

因此,当您将
method1
作为
secondclass
的方法调用时,您将调用
“method2”
,因为这是您覆盖该方法要执行的操作,而不是遵循从
firstclass
继承的方法


编辑:mabac是正确的,因为
secondclass
中的
method1
不接受任何参数,因此将引发异常,因为该方法的参数是
“abc”

如果您希望调用这两个方法,则需要使用在
firstclass
中调用该方法

  • 如链接文档中所述,为了实现这一点,
    firstclass
    需要是一个新样式的类,因此应该从
    对象继承

  • 另外,如上所述,
    firstclass
    中的方法需要一个参数,因此我传入了一个伪参数:

  • 还要注意,我已经将类名更改为CapWords样式- 看

输出:

method1 is invoked
method2 is invoked

由于secondclass中的方法不接受任何参数,因此实际上会出现错误。
method1 is invoked
method2 is invoked