0

hellow im write the code above :

class val:

    def __init__(self, value, TYPE):
        val.value = value
        val.TYPE = TYPE

u = val([1, -3], 'polar')
v = val([0, 2], 'cartesian')

print(u.value)
print(u.TYPE)
print(v.value)
print(v.TYPE)

but the output is :

[0, 2]
cartesian
[0, 2]
cartesian

why the first instance has changed (I expected to get [1, -3] in the first row)

  • 1
    Because you are referencing `val` in your `__init__()` instead of `self`. – Ghoti Aug 13 '21 at 21:45
  • Simply change `val.value = value` to `self.value = value` and `val.TYPE = TYPE` to `self.TYPE = TYPE`. – Ghoti Aug 13 '21 at 21:46

4 Answers4

1

You are referring to the class where you should be referring to the object passed to __init__. As a result you repeatedly change the values of two class attributes, rather than setting instance attributes on separate instances.

class val:

    def __init__(self, value, TYPE):
        self.value = value
        self.TYPE = TYPE

A couple of conventions:

  1. User-defined classes are capitalized

  2. To avoid shadowing a built-in name, append a _ to the name.

    class Val:
        def __init__(self, value, type_):
            self.value = value
            self.type = type_
    

(You can use type as an attribute name without shadowing the built-in name type.)

chepner
  • 497,756
  • 71
  • 530
  • 681
0

You need to change "val.value" to "self.value", etc.

Mark Lavin
  • 1,002
  • 1
  • 15
  • 30
0

The reason why it changed is because you used the class name val and set its fields instead of the object itself. val refers to the class. Use self to refer to an instance of this class.

Code fix;

def __init__(self, value, TYPE):
    self.value = value
    self.TYPE = TYPE
waykiki
  • 914
  • 2
  • 9
  • 19
0

You assigned your variables to the class val, not the instance self. In python, an instance lookup falls back to the class if the variable isn't there. Your second instance creation overwrote the class level variables and your later references to the instance fell back to that overwritten value. Use the self instance reference instead.

class val:

    def __init__(self, value, TYPE):
        self.value = value
        self.TYPE = TYPE

u = val([1, -3], 'polar')
v = val([0, 2], 'cartesian')

print(u.value)
print(u.TYPE)
print(v.value)
print(v.TYPE)
tdelaney
  • 73,364
  • 6
  • 83
  • 116