Python Forum

Full Version: Unexplained Phenomenon with Objects
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Consider the following class:
class a:
  def __init__(self,T):
    self.T=T
Now, if I set
x=a(3)
y=a(4)
we find that x.T is 4, but their pointers are different. Furthermore, if I set x.T=5, y.T remains as 4. If I again produce another variable z=a(6), we find that y.T is 6 as well, but x.T is still 5.

Is this a feature of Python or maybe it's my IDE (I'm using Spyder 3.7).
the code you show cannot produce the result you describe.
class Foo:
  def __init__(self, t):
    self.t = t


spam = Foo(3)
eggs = Foo(4)

# check values
print(f'spam.t = {spam.t}')
print(f'eggs.t = {eggs.t}')

# change value
eggs.t = 6

# check values
print('----------')
print(f'spam.t = {spam.t}')
print(f'eggs.t = {eggs.t}')


bar = Foo(7)

# check values
print('-----------')
print(f'spam.t = {spam.t}')
print(f'eggs.t = {eggs.t}')
print(f'bar.t = {bar.t}')
Output:
spam.t = 3 eggs.t = 4 ---------- spam.t = 3 eggs.t = 6 ----------- spam.t = 3 eggs.t = 6 bar.t = 7
probably there is something else/different in the code you are running.