Skip to content

Instantly share code, notes, and snippets.

@pouyamn
Created August 2, 2019 10:06
Show Gist options
  • Save pouyamn/84ab6b47a3c0d82d053c4eb94ef2b09f to your computer and use it in GitHub Desktop.
Save pouyamn/84ab6b47a3c0d82d053c4eb94ef2b09f to your computer and use it in GitHub Desktop.
Yet another understanding Python classes and instanses, using a simulated interpreter approach [WIP]

Yet another understanding Python classes and instanses, using a simulated interpreter approach

class Foo:
  bar = "class attribute"
  
  def __init__(self):
    self.ham="instance attribute"
  
  def baz(self):
    self.baz = "changed instance attribute"
  
  @classmethod
  def qux(cls):
    cls.bar = "changed class attribute"

  @staticmethod
  def spam():
    print("I've got no reference")

Results in :

memory[0]=<class 1>
memory[1]=<string 1>
memory[2]=<function 1>
memory[3]=<function 2>
memory[4]=<function 3>
memory[5]=<function 4>

namespace.Foo=memory[0]
namespace.Foo.__init__=memory[1]
namespace.Foo.bar=memory[2]
namespace.Foo.baz=memory[3]
namespace.Foo.qux=memory[4]
namespace.Foo.spam=memory[5]

then foo=Foo() results in:

after __new__() run:
namespace.foo=memory[6]
namespace.foo.__init__=namespace.Foo.__init__=memory[1]
namespace.foo.bar=namespace.Foo.bar=memory[2]
namespace.foo.baz=namespace.Foo.baz=memory[3]
namespace.foo.qux=namespace.Foo.qux=memory[4]
namespace.foo.spam=namespace.Foo.spam=memory[5]

after __init__() run:
memory[7]=<string 2>
namespace.foo.ham=memory[7]

and eggs=Foo() results in:

after __new__() run:
namespace.eggs=memory[8]
namespace.eggs.__init__=namespace.Foo.__init__=memory[1]
namespace.eggs.bar=namespace.Foo.bar=memory[2]
namespace.eggs.baz=namespace.Foo.baz=memory[3]
namespace.eggs.qux=namespace.Foo.qux=memory[4]
namespace.eggs.spam=namespace.Foo.spam=memory[5]

after __init__() run:
memory[9]=<string 3>
namespace.eggs.ham=memory[9]

The object

I refer to object as in Object Oriented Propgramming, not Python's object class, not instances of a class, not Django's .objects not desk or paperclips.

memory model

memory is a fictional model which represents parts of memory that we are interested to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment