Python Forum
Unexplained Phenomenon with Objects
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unexplained Phenomenon with Objects
#1
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).
Reply
#2
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unexplained Invalid syntax Error cybertooth 5 3,244 Aug-02-2021, 10:05 AM
Last Post: cybertooth

Forum Jump:

User Panel Messages

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