Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change method defaults in Python?

I'm building a class, Child, that inherits from another class, Parent. The Parent class has a loadPage method that the Child will use, except that the Child will need to run its own code near the end of the loadPage function but before the final statements of the function. I need to somehow insert this function into loadPage only for instances of Child, and not Parent. I was thinking of putting a customFunc parameter into loadPage and have it default to None for Parent, but have it default to someFunction for Child.

How do I change the defaults for the loadPage method only for instances of Child? Or am I going about this wrong? I feel like I may be overlooking a better solution.

class Parent():
    def __init__(self):
        # statement...
        # statement...
    def loadPage(self, pageTitle, customFunc=None):
        # statement...
        # statement...
        # statement...
        if customFunc:
            customFunc()
        # statement...
        # statement...

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
        self.loadPage.func_defaults = (self.someFunction)  #<-- This doesn't work
like image 774
Tanner Semerad Avatar asked Dec 31 '25 11:12

Tanner Semerad


2 Answers

For such things, I do it in a different way :

class Parent():
   def loadPage(self, pageTitle):
      # do stuff
      self.customFunc()
      # do other stuff

   def customFunc(self):
      pass

class Child(Parent):

   def customFunc(self):
      # do the child stuff

then, a Child instance would do the stuff in customFunc while the Parent instance would do the "standard" stuff.

like image 93
Cédric Julien Avatar answered Jan 02 '26 03:01

Cédric Julien


Modifying your method as little as possible:

class Parent(object):
    def __init__(self):
        pass
    def loadPage(self, pageTitle, customFunc=None):
        print 'pageTitle', pageTitle
        if customFunc:
            customFunc()

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
    def loadPage(self, pagetitle, customFunc = None):
        customFunc = self.someFunction if customFunc is None else customFunc
        super(Child, self).loadPage(pagetitle, customFunc)
    def someFunction(self):
        print 'someFunction'


p = Parent()
p.loadPage('parent')
c = Child()
c.loadPage('child')
like image 44
agf Avatar answered Jan 02 '26 03:01

agf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!