Created
November 15, 2012 13:10
-
-
Save pkqk/4078580 to your computer and use it in GitHub Desktop.
python class inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| 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