Aug-30-2020, 02:49 PM
(This post was last modified: Aug-30-2020, 02:50 PM by deanhystad.)
(Aug-29-2020, 02:43 PM)jefsummers Wrote: Also remember that a class can contain functions (methods) and while a dictionary _can_ do that, it is less common for them to do so.Less common, but it is exactly how python stores methods for the class. Unless you define the class to use slots, Python classes contain a dictionary named __dict__. This dictionary contains all the class attributes; class variables and methods.
I think looking at what goes in __dict__ is very informative.
class Scope: one = 1 def __init__(self): self.two = 2 def three(self): self._three = 3 scope = Scope() scope2 = Scope() scope2.three() print('Scope class:', [item for item in Scope.__dict__]) print('scope instance:', [item for item in scope.__dict__]) print('scope2 instance:', [item for item in scope2.__dict__])
Output:Scope class: ['__module__', 'one', '__init__', 'three', '__dict__', '__weakref__', '__doc__']
scope instance: ['two']
scope2 instance ['two', '_three']
Classes have a __dict__ and so does every instance of the class. The class __dict__ and the instance __dict__ are different. Notice that the class __dict__ knows about the class variables ('one') and methods ('__init__', 'three'). The instance __dict__ only knows about instance variables. scope1 knows about 'two' which is an instance variable set in the __init__ method. scope2 also knows about '_three' which is an instance variable created when the three() method was called. I could also add an instance variable externallyscope.four=4This would add an instance variable to the instance scope, but would not affect the class or any other instance.