Skip to content

Instantly share code, notes, and snippets.

@ansrivas
Last active February 26, 2018 12:15
Show Gist options
  • Select an option

  • Save ansrivas/94aa8785a378769099eff0266b718a89 to your computer and use it in GitHub Desktop.

Select an option

Save ansrivas/94aa8785a378769099eff0266b718a89 to your computer and use it in GitHub Desktop.
Python subclassing explained
  1. Case1:

    Define Base.init(self)

class Base(object):
    def __init__(self):
        self.anattribute = 23
class Derived(Base):
    def __init__(self):
        Base.__init__(self)
        self.anotherattribute = 45

# Expect 23 here as an output
Derived().anattribute
# 23
  1. Case2: Don't define Base.init(self)
class Base(object):
    def __init__(self):
        self.anattribute = 23
class Derived(Base):
    def __init__(self):
        self.anotherattribute = 45

# Expect an exception here
Derived().anattribute
  1. Case3:

    Don't define Derived.init(self)

class Base(object):
    def __init__(self):
        self.anattribute = 23
class Derived(Base):
    pass

# Didn't define __init__ so automatically Base.__init__.py will be called
Derived().anattribute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment