How does `edit_message` know to reference the `Message` class?

Here’s a code to an exercise in the lesson:

class Message:
  def __init__(self, sender, recipient, text):
    self.sender = sender
    self.recipient = recipient
    self.text = text

class User:
  def __init__(self, username):
    self.username = username
    
  def edit_message(self, message, new_text):
    if message.sender == self.username:
      message.text = new_text

What I don’t get is how does Python know what message.sender refers to?? I thought in order to refer to the object, it would be self.sender. Similarly, I don’t know get what message.text refers to, and why is it not self.text.

Thanks.Preformatted text

1 Like

but message parameter of edit_message method is an instance of Message class. self within the User class refers to instance of User class.

so you need to instance of Message class to edit_message method

i recommend creating instances and calling the method(s), to see everything works. Let me know if you need more help.

1 Like

Thanks for your reply.

I think where I was confused was how did message in the edit_message method of the User class became an instance of the Message class. I thought to make an instance, you’d have to declare the instance explicitly. Is it the .sender part that makes message.sender attribute an instance of the Message class, or the message part of the message.sender that makes this attribute an instance of the Message class?

thanks again for your response.

It doesn’t become a Message, that’s what the user of the method is supposed to send it, similar to how a and b do not become numbers in this function, that’s what the user is supposed to provide:

def add(a, b):
    return a + b

Sidenote: “declare” is a rarely used word in python, we skip that step altogether, we don’t declare the existence of things, we just put them there. For example, we don’t have undefined variables, because that would require declaring them (without defining them), which we don’t.
There’s an exception to this with function variables, those variables do get created before anything else happens:

def f():
    print(a)  # undefined, but does exist
    a = 5

# in contrast to:
print(a)  # doesn't exist at all
a = 5

yes, currently messageof edit_message method is just a parameter. I thought i didn’t have to explain parameters vs arguments

when you call the method, you can pass an instance of Message class for the message parameter of edit_message method

that is why i recommend, you actual attempt to call the methods, to see how they work

message is a parameter of edit_message method which belongs to User class. how come suddenly sender which belongs to Message class got related to message parameter out of no where?

1 Like

Following is some example code that instantiates the User and Message classes to demonstrate how this works:

monty = User("Monty")
eric = User("Eric")
# Create the Message instance
montyMessage = Message("Monty", "Eric", "I don't like Spam!")
print(montyMessage.text)
# Edit the Message instance
monty.edit_message(montyMessage, "I love Spam!")
print(montyMessage.text)

Notice that we have created an instance of Message and assigned it to montyMessage. That instance has a sender instance variable. When we call the edit_message method from monty, which is a User, we pass montyMessage to that method. Now the edit_message method can access the sender instance variable of montyMessage.

The output is:

I don't like Spam!
I love Spam!
3 Likes

it makes so much sense now :grinning:…thanks a lot

2 Likes
class Message:
  def __init__(self, sender, recipient, text):
    self.sender = sender
    self.recipient = recipient
    self.text = text

class User:
  def __init__(self, username):
    self.username = username
    
  def edit_message(self, message, new_text):
    if message.sender == self.username:
      message.text = new_text
      
class Admin(User):
  def edit_message(self, message, new_text):
    if message.sender != self.username:
      try:
        message.text = new_text
      except User:
        print("Do something")
  

This worked, but does this make sense to anyone or am I overdoing my code?

Hello Stem, please help me with this. I understood class definition and inheritance but not until I met this code. I became confused in an instant. I did’t even know what possible thing I could do with the class.

class Message:
  def __init__(self, sender, recipient, text):
    self.sender = sender
    self.recipient = recipient
    self.text = text

class User:
  def __init__(self, username):
    self.username = username
    
  def edit_message(self, message, new_text):
    if message.sender == self.username:
      message.text = new_text
      
    return new_text
      
class Admin(User):
  def edit_message(self, message, new_text):
    message.text = new_text

please, can you tell me what happened here. Thanks dear, I really appreciate.

I recommend you to try to make some class instance and actually try to call the edit_message method, see if you can get it to work. That will teach you the most. Let me know where you get stuck, so i can help you further.

thanks for the trouble Stem, I failed to read the solutions here before asking. It’s now clear to me. But I have to mention that I couldn’t stop laughing at the way people got confused here, hahahahahha, that little code almost made me crazy. I think it should just be noted there that “message” is expected to be an object of the “Message class”. Mystery solved… Thanks again Stem, you got our back.

hello Applple… thanks for the illustration you gave. mehn, you saved someone fromm going crazy.

the drawback of a dynamic typed language, if you have a static typed language you can define what type the parameter should be, that can really help.

fortunately, python slowly starts to support this as well:

https://docs.python.org/3/library/typing.html

the interpreter disregards the type hints, but there are tools which can check your types match the expected type

That is great. Thanks again.

strong/weak and static/dynamic are different things
it’s about whether the language allows non-sensical operations (python doesn’t, so it’s strongly typed, javascript does, so it’s weakly typed)

Some examples of javascript’s weak typing:

> [1]['0']  // So uhm are array keys numbers or strings?
1
> [2, 10].sort()  // sorts by string representation
[ 10, 2 ]
> [1] + [3]  // let's convert these arrays to string before concatenating them
'13'
> undefined + 'hello'
'undefinedhello'

:man_facepalming:

1 Like

`
class Color:
def init (self, red, blue, green):
self.red = red
self.blue = blue
self.green = green

def repr (self):
return “Color with RGB = ({red}, {blue}, {green})”.format(red=self.red, blue=self.blue, green=self.green)

def add(self, other):
“”"
Adds two RGB colors together
Maximum value is 255
“”"
new_red = min(self.red + other.red, 255)
new_blue = min(self.blue + other.blue, 255)
new_green = min(self.green + other.green, 255)

return Color(new_red, new_blue, new_green)

red = Color(255, 0, 0)
blue = Color(0, 255, 0)

magenta = red.add(blue)
print(magenta
`

Hello everybody , please help explain this code to me. it is breaking my head.

`
class Color:
def add(self, other):
“”"
Adds two RGB colors together
Maximum value is 255
“”"
new_red = min(self.red + other.red, 255)
new_blue = min(self.blue + other.blue, 255)
new_green = min(self.green + other.green, 255)

return Color(new_red, new_blue, new_green)

`

This one too is confusing. I get the basic idea of what the “add” method is supposed to do but I do not just get how all this got done. thanks all

Hi @eldics,

Code should be formatted when it is posted so that it exhibits indentation and other details. See How to ask good questions (and get good answers) for information on how to format code.

The add method of Color has been formatted for posting here:

  def add(self, other):
    """
    Adds two RGB colors together
    Maximum value is 255
    """
    new_red = min(self.red + other.red, 255)
    new_blue = min(self.blue + other.blue, 255)
    new_green = min(self.green + other.green, 255)
    return Color(new_red, new_blue, new_green)

Each color has a red, green, and blue component. To add two colors together, we sum the two values that apply to each component to calculate the value of that component in the result. However the maximum allowed value for each component is 255. Therefore, if the sum of the two values for any component exceeds 255, we need to reduce the result to 255 for that component. In the add method, above, we add together the two values for each component, and use the min function to prevent the result from exceeding 255. If the two component values sum to less than 255, that sum is the minimum, and becomes part of the result. However, if that sum exceeds 255, then 255 is the minimum, and that becomes part of the result.

wow… this code has become crystal clear to me. what was I missing? I think I failed to recognize what the min function actually did there. All along, I thought it was returning two values. I played all the code snippet on that exercise and I now understand better. thanks appylpye.

1 Like

I still don’t get one thing

class Message:
  def __init__(self, sender, recipient, text):
    self.sender = sender
    self.recipient = recipient
    self.text = text

class User:
  def __init__(self, username):
    self.username = username
    
  def edit_message(self, message, new_text):
    if message.sender == self.username:
      message.text = new_text

When we execute if message.sender == self.username how does the compiler knows what .sender is. It is defined in another class. Does classes can acess each other’s methods just like that?