Most “pythonic” way of organising class attributes, constructor arguments and subclass constructor defaults?

后端 未结 1 1955
生来不讨喜
生来不讨喜 2020-12-14 02:25

Being relatively new to Python 2, I\'m uncertain how best to organise my class files in the most \'pythonic\' way. I wouldn\'t be asking this but for the fact that Python se

相关标签:
1条回答
  • 2020-12-14 03:17
    • If attributes will vary from instance to instance make them instance attribute i.e. create them inside__init__ using self else if they need to be shared between class instances like a constant, put them at class level.

    • If your class really need to pass, so many arguments in __init__, let derive class use argument list and keyword arguments e.g.

    class Dog(ClassWithLotsOfAttributes):
        def __init__(self, *args , **kwargs):
            super(ClassWithLotsOfAttributes,    self).__init__(*args , **kwargs)
            self.coolness = "really cool!!!
    • No need of passing all variables except few important ones, in __init__, class can assume some defaults and user can change them later on if needed.
    • Use 4 spaces instead of tab.

    • if you need to add an extra arg bite, to Dog and keyword arg old too

    class CoolDog(ClassWithLotsOfAttributes):
        def __init__(self, bite, *args , **kwargs):
            self.old = kwargs.pop('old', False) # this way we can access base class args too
            super(ClassWithLotsOfAttributes,    self).__init__(*args , **kwargs)
            self.bite = bite
            self.coolness = "really really cool!!!

    various ways you useCoolDog

    CoolDog(True)
    CoolDog(True, old=False)
    CoolDog(bite=True, old=True)
    CoolDog(old=True, bite=False)
    
    0 讨论(0)
提交回复
热议问题