Python Forum
two different objects, but somehow the values are shared between them
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
two different objects, but somehow the values are shared between them
#7
(Apr-19-2018, 08:09 PM)RaphaelMG Wrote: Im used to C (C# and C++)

Ok, so what you're doing, in terms of those other languages, is having a static variable position that's unbound from any instance. In python, they're called class attributes/methods instead of static, but it's essentially the same thing. In order to have instance variables, they'd need to be defined in the __init__ method, not outside of there.

Here's some example code to try to show the difference:
>>> class Spam:
...   # class attribute, shared by all instances
...   things = []
...   def add(self, thing):
...     self.things.append(thing)
...     return self.things
...
>>> eggs = Spam()
>>> eggs.add("first")
['first']
>>> ham = Spam()
>>> ham.add("second")
['first', 'second']
>>> Spam.things
['first', 'second']
>>>
>>> class Bike:
...   def __init__(self):
...     self.things = []
...   def add(self, thing):
...     self.things.append(thing)
...     return self.things
...
>>> two_wheels = Bike()
>>> two_wheels.add("first")
['first']
>>> four_wheels = Bike()
>>> four_wheels.add("second")
['second']
>>> Bike.things
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Bike' has no attribute 'things'
Reply


Messages In This Thread
RE: two different objects, but somehow the values are shared between them - by nilamo - Apr-20-2018, 05:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Shared reference of variables... Denial 1 1,435 Aug-29-2020, 01:52 PM
Last Post: snippsat
  How to install and use a shared libary, via a .dll? ninjaisfast 0 1,304 Jul-09-2020, 03:23 PM
Last Post: ninjaisfast
  Divisors shared the second numbers mircea_dragu 1 2,057 Feb-07-2019, 10:09 PM
Last Post: ichabod801
  running just one process shared among uses Skaperen 3 3,006 Aug-07-2018, 12:12 AM
Last Post: Skaperen
  Shared reference and equality zyo 3 3,183 Jun-30-2018, 07:10 PM
Last Post: ljmetzger
  Shared queues l00p1n6 3 3,005 May-15-2018, 01:38 PM
Last Post: DeaD_EyE
  updating values in objects mercator 2 3,061 Dec-07-2017, 07:41 PM
Last Post: mercator

Forum Jump:

User Panel Messages

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