Updated object attribute in python class but not reflected

consider my simple class

class stud():
    def __init__(self,a,b):
        self.name=a
        self.mark=b
        self.message=self.name + ' ' +str(self.mark)

s1=stud('student1',40)
print s1.message  --->output=student1 40 
s1.name='student2'
print s1.message ----> output =student1 40 , but i expected student2 40

My question here is why, when I printed self.message [after changing the attribute of the name of the object], did it print the old value? I know that the init method is called only once during the creation of the object, and the name attribute is set to "student1" at this time. But I change it to the next line, and again print self.message should not display the new value?

Why does this self.message not update the changed value?

+4
source share
4 answers

Tracking progress.

s1=stud('student1',40)

It sets

  • s1.name to "student1"
  • s1.mark to 40
  • s1.message to "student1 40"

. . . . , . , NO IDEA, . , , name mark. , , , "student1 40".

print s1.message

student1 40 ()

s1.name='student2'

. .

print s1.message

s1.message, student1 40.

- s1.message - . , , , , . , , Python .

, :

class stud():
    def __init__(self,a,b):
        self.name=a
        self.mark=b

    @property
    def message():
        return self.name + ' ' +str(self.mark)
+5

, self.message init, s1.name = student2, self.name, self.message .

self.message, - .

:

class stud():
    def __init__(self,a,b):
        self.name=a
        self.mark=b

    def the_message(self):
        self.message = self.name + ' ' + str(self.mark)
        return self.message

s1 = stud('student1',40)
print s1.the_message() 

s1.name='student2'
print s1.the_message() 

:

student1 40
student2 40
+3

, name, mark message.

name, , .

:

self.message=self.name + ' ' +str(self.mark)

, .

    def get_message(self):
        return self.name + ' ' + str(self.mark)


s1 = Stud('student1', 40)
print(s1.message)
s1.name = 'student2'
print(s1.get_message())

, object ( Python 2).

:

class Stud(object):
    def __init__(self, a, b):
        self.name = a
        self.mark = b

    @property
    def message(self):
        return self.name + ' ' + str(self.mark)

s1 = Stud('student1', 40)
print(s1.message)
s1.name = 'student2'
print(s1.message)

:

  • class names must be in CamelCase,
  • variable and function names must be in snake_case.
+2
source

Since you only changed the attribute name, not message, so it still prints the same message.

You need to determine messagehow function, not attribute. Go ahead and try.

+1
source

Source: https://habr.com/ru/post/1691534/


All Articles