Python Class vs. Module Attributes

前端 未结 4 735
抹茶落季
抹茶落季 2020-12-29 09:47

I\'m interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up

4条回答
  •  無奈伤痛
    2020-12-29 10:27

    what is a good use case for class attributes

    Case 0. Class methods are just class attributes. This is not just a technical similarity - you can access and modify class methods at runtime by assigning callables to them.

    Case 1. A module can easily define several classes. It's reasonable to encapsulate everything about class A into A... and everything about class B into B.... For example,

    # module xxx
    class X:
        MAX_THREADS = 100
        ...
    
    # main program
    from xxx import X
    
    if nthreads < X.MAX_THREADS: ...
    

    Case 2. This class has lots of default attributes which can be modified in an instance. Here the ability to leave attribute to be a 'global default' is a feature, not bug.

    class NiceDiff:
        """Formats time difference given in seconds into a form '15 minutes ago'."""
    
        magic = .249
        pattern = 'in {0}', 'right now', '{0} ago'
    
        divisions = 1
    
        # there are more default attributes
    

    One creates instance of NiceDiff to use the existing or slightly modified formatting, but a localizer to a different language subclasses the class to implement some functions in a fundamentally different way and redefine constants:

    class Разница(NiceDiff): # NiceDiff localized to Russian
        '''Из разницы во времени, типа -300, делает конкретно '5 минут назад'.'''
    
        pattern = 'через {0}', 'прям щас', '{0} назад'
    

    Your cases:

    • constants -- yes, I put them to class. It's strange to say self.CONSTANT = ..., so I don't see a big risk for clobbering them.
    • Default attribute -- mixed, as above may go to class, but may also go to __init__ depending on the semantics.
    • Global data structure --- goes to class if used only by the class, but may also go to module, in either case must be very well-documented.

提交回复
热议问题