Difference between defining a member in __init__ to defining it in the class body in python?

后端 未结 3 517
广开言路
广开言路 2021-01-12 11:37

What is the difference between doing

class a:
   def __init__(self):
       self.val=1

to doing

class a:
   val=1
   def __         


        
3条回答
  •  旧巷少年郎
    2021-01-12 12:42

    Others have explained the technical differences. I'll try to explain why you might want to use class variables.

    If you're only instantiating the class once, then class variables effectively are instance variables. However, if you're making many copies, or want to share state among a few instances, then class variables are very handy. For example:

    class Foo(object):
        def __init__(self):
            self.bar = expensivefunction()
    
    myobjs = [Foo() for _ in range(1000000)]
    

    will cause expensivefunction() to be called a million times. If it's going to return the same value each time, say fetching a configuration parameter from a database, then you should consider moving it into the class definition so that it's only called once and then shared across all instances.

    I also use class variables a lot when memoizing results. Example:

    class Foo(object):
        bazcache = {}
    
        @classmethod
        def baz(cls, key):
            try:
                result = cls.bazcache[key]
            except KeyError:
                result = expensivefunction(key)
                cls.bazcache[key] = result
            return result
    

    In this case, baz is a class method; its result doesn't depend on any instance variables. That means we can keep one copy of the results cache in the class variable, so that 1) you don't store the same results multiple times, and 2) each instance can benefit from results that were cached from other instances.

    To illustrate, suppose that you have a million instances, each operating on the results of a Google search. You'd probably much prefer that all those objects share those results than to have each one execute the search and wait for the answer.

    So I'd disagree with Lennart here. Class variables are very convenient in certain cases. When they're the right tool for the job, don't hesitate to use them.

提交回复
热议问题