Skip to content
Advertisement

self in Python references to variable rather than the class [closed]

So, I’m trying to code an observer pattern in Python. Main method:

JavaScript
JavaScript
JavaScript

As far as I understand the self parameter, it references to it’s own instance. So if I type it in a Subject object, it would reference to that. Yet I get this error message:

JavaScript

I don’t understand why it references to the message variable in an Subject method, shouldn’t it reference to the Newsletter (Subject class) object?

I tried to google my problem and read into the self parameter, yet without any success. Everything I read seemed to support my theory, that the Newsletter object should be referenced, not the string message.

As I am fairly new to python there might be some other problems, i would be happy if you have other tips too :)

Advertisement

Answer

JavaScript

The mistake is the way you define your parameters here. The fact is the first parameter will always be what you know as self – the Object. So by having a message as your first parameter, message will be used as the parameter for your object. e.g.: you could do message.ObserverList. Make sure to always have self as the first parameter.

So..

JavaScript

and

JavaScript

should do the trick

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement