Skip to content

Instantly share code, notes, and snippets.

@pkqk
Created November 15, 2012 13:10
Show Gist options
  • Select an option

  • Save pkqk/4078580 to your computer and use it in GitHub Desktop.

Select an option

Save pkqk/4078580 to your computer and use it in GitHub Desktop.
python class inheritance
class User(object):
def __init__(self, email, password, brands, dashboardbrands, allBrands, active=True):
self.email = email
self.password = password
self.brands = brands
self.dashboardbrands = dashboardbrands
self.allBrands = allBrands
self.active = active
class NormalUser(User):
def __init__(self, *args, **kwargs):
self.isStaff = False
self.isSuper = False
super(User, self).__init__(*args, **kwargs)
# or this way if you're only ever inheriting from one thing, or it's an old style class*
#User.__init__(self, *args, **kwargs)
# * a class made without having object in the inheritance list.
"""
The reason this is all necessary
the super call in Bar.__init__ returns BaseBar so you can call the BaseBar.__init__ method
but
the super call in BaseBar.__init__ doesn't return object, even though that's what BaseBar inherits from
it looks at what self is which has 2 ancestors (BaseBar, Foo), BaseBar has already been returned so it now returns Foo
from then on it goes up the inheritance chain of Foo until it reaches object.
"""
class BaseFoo(object):
def __init__(self, foo):
self.foo = foo
super(BaseFoo, self).__init__()
class Foo(BaseFoo):
def __init__(self, foo, baz):
super(Foo, self).__init__(foo)
self.baz = baz
class BaseBar(object):
def __init__(self, bar, *args):
self.bar = bar
super(BaseBar, self).__init__(*args)
class Bar(BaseBar, Foo):
def __init__(self, bar):
super(Bar, self).__init__(bar, "foo", "baz")
b = Bar("bar")
assert b.bar == "bar"
assert b.foo == "foo"
assert b.baz == "baz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment