Python Forum
class definition and problem with a method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
class definition and problem with a method
#2
Remember that variables are not objects in Python, they are references to objects. "p3 = Punkt()" creates a variable named "p3" and assigns it the newly created Punkt() object. When you call p3.add(p1, p1), self is a variable inside the method/function Punkt.add(). Initially it references the same object referenced by p3. When you assign a new value to self inside of add() (self = Punkt()), self no longer refers to the same object as p3. Changes made to self will not affect p3. Your function returns the new Punkt object, but you ignore the return value.

Your code would work if you wrote: p3 = p3.add(p1, p2). This reassigns p3 to refer to the new object that was created in add(). Another way to fix this is what you did by accident. Don't reassign self so it continues to refer to the same object as p3. Changes made to self are not changes made to p3, because they both reference the same object (changes are actually made to the object, not to self or p3).

But that is not what you want to do. You want to override the + operator.
class Punkt():
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return f'( {self.x} | {self.y} )'

    def __add__(self, p2):
        """Override the + operator."""
        return Punkt(self.x + p2.x, self.y + p2.y)


p1 = Punkt(17, 12)
p2 = Punkt(-9,-4)
p3 = p1 + p2
print(f"Punkt 3: {p3}")
Output:
Punkt 3: ( 8 | 8 )
Reply


Messages In This Thread
RE: class definition and problem with a method - by deanhystad - Apr-01-2024, 03:34 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Accessing method attributes of python class Abedin 6 1,344 Apr-14-2025, 07:02 AM
Last Post: buran
  __eq__ method related problem Tsotne 6 1,103 Mar-09-2025, 03:48 PM
Last Post: Tsotne
  super() and order of running method in class inheritance akbarza 7 2,634 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  problem usage of static method akbarza 5 2,639 Feb-03-2024, 07:43 AM
Last Post: paul18fr
  mutable argument in function definition akbarza 1 1,295 Dec-15-2023, 02:00 PM
Last Post: deanhystad
  error occuring in definition a class akbarza 3 2,436 Nov-26-2023, 09:28 AM
Last Post: Yoriz
  determine parameter type in definition function akbarza 1 1,319 Aug-24-2023, 01:46 PM
Last Post: deanhystad
  [split] Explain the python code in this definition Led_Zeppelin 1 1,392 Jan-13-2023, 10:20 PM
Last Post: deanhystad
  Using one child class method in another child class garynewport 5 3,366 Jan-11-2023, 06:07 PM
Last Post: garynewport
  Explain the python code in this definition Led_Zeppelin 1 1,794 Oct-27-2022, 04:04 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020