Python Forum
namespaces when defining a class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
namespaces when defining a class
#1
apparently, the global name-space is not the space where the method names exist. there appear to be as many as 4 name-spaces involved. there are 2 created just by defining the class: the global space and the class space. then when an object instance is created from this class, there are 2 more name spaces. each object instance has 2 name-spaces, just for it. one of these is a replica of the class name-space and a reference to it is given to methods as the 1st argument, commonly named "self". the other is the usual local name-space which is created at invocation of a method. my curiosity is about the global name-space. the class name-space is also of some interest. the big thing i wonder about is can information be shared between instances in either of these? what if i define a dictionary there? will i be able to store values and object there an fetch them back out, later, in a different invocation and/or a different instance?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Members of the class namespace are shared by all the instances, just like static members in C++ for example, as long as you access them for reading. But if you write a.x when a is an instance of A, it will create an member in the instance's namespace
>>> class A:
...     x = 'spam'
... 
>>> a = A()
>>> b = A()
>>> a.x
'spam'
>>> a.x = 'bar'
>>> a.x
'bar'
>>> b.x
'spam'
Reply
#3
what if a dictionary already exists in the class namespace? can i add a new member to that dictionary? i don't consider that to be "just reading", although technically, it is another namespace and i am just reading a reference to it from the class namespace. i do this in globals, too (create a dictionary or list there to easily put stuff there). the thing is, documentation that says "for reading only" could turn people away when they are looking for a solution that solves.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Of course, using a container in the class' namespace is a good way to share a place to read and write for all the instances.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020