On 10/17/2018 11:13 PM, me.vi...@gmail.com wrote:
Hi,

I tried using namedtuples and just found a behaviour which I am not able to
conclude as correct behaviour.

from collections import namedtuple

(n, categories) = (int(input()), input().split())
Grade = namedtuple('Grade', categories)
Grade.ID = 1
#print(Grade.ID)
ob = Grade(10, 50)
print(ob.ID)
print(ob.MARKS)
ob1 = Grade(20, 100)
print(ob1.ID)

2
ID MARKS
1
50
1
100


If we set GRADE.ID =1 ,

Whoa!  Don't do that.  The Grade object created with the namedtuple call is a class, and part of it's internal implementation is stored in Grade.ID.  Try these lines:

>>> print(Grade)
<class '__main__.Grade'>
>>> print(Grade.ID)
<property object at 0x7f1867e877c8>
>>>

By reassigning Grade.ID, you are sabotaging the internals of the class.  Without looking at those internals, it's not really a surprise that things stop working after you destroy the <property object ...>  it so carefully stored in Grade.ID.


So now the real question is:  What were you trying to accomplish with the assignment?  Tell us, and let's see if we can find a way to accomplish yor goal without wrecking the internals of the Grade class.


Gary Herron


it has impact on all variables. Is this behaviour
just like class variable and it has global scope.
I expected ob.ID and ob1.ID to be 10.

Correct me if Iam wrong.
Appreciate any quick response.

Kind Rgds,
Vinu

--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to