Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pythonic way to skip parent method?

class A:
  def open_spider(self, spider):
    #do some hacking

class B(A):
  def open_spider(self, spider):
    super(B, self).open_spider(spider)
    #something else

Now I want C to call A's method but not B's, which can be done at least in two ways:

  class C(B):
    def open_spider(self, spider):
      A.open_spider(self, spider)
      #do things

  class C(B):
    def open_spider(self, spider):
      super(B, self).open_spider(spider)
      #do things
like image 996
VladimirLenin Avatar asked Oct 07 '16 13:10

VladimirLenin


People also ask

How do you override a parent in Python?

Overriding a method in the same class is not allowed. So, you need to do that in the child class by implementing the Inheritance concept. If you want to override the Parent Class method, create a function in the Child with the same name and number of parameters. This is called function overriding in Python.

How do you avoid inheritance in Python?

The way to "avoid" inheritance here would be to rename _private_var and make it a class-private name. i.e. __private_var . If you do this, running your code will cause an AttributeError: 'Child' object has no attribute '_Parent__private_var' (note the _Parent prefix automatically added).

What does super () do in Python?

The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.

How do you call parent method in child class?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.


2 Answers

You can do it using the second way. But I must say that part where child skips parent method and call grandparent instead is wrong and you should take a look on your design once again and think about it.

like image 200
Alex Avatar answered Sep 18 '22 00:09

Alex


Use the second method; this is one reason why super takes a class as its first argument.

like image 39
chepner Avatar answered Sep 19 '22 00:09

chepner