0

Even after reading the answer of @ncoghlan in Python nonlocal statement in a class definition (that I didn't get well, by the way), I'm not able to understand this behavior.

# The script that fails and I can't explain such fail
class DW:

   def r():  return 3
   def rr(): return 2 + r()
   y = r()
   x = rr()

# a solution that I don't like: I don't want high order functions
class W:

   def r():  return 3
   def rr(r): return 2 + r()
   y = r()
   x = rr(r)

Class bodies acts more or less like a scripts. This feature is some what strange to me yet. Around this, I have some newbie questions. I thank you in advance if you help me to get them.

  • Can I define functions inside the body of a class, use them and delete them before the ending of the class definition? (In this case, naturally, the deleted functions will not exist to instances of such class)

  • How can I promote a better visibility between functions and properties inside a class definition, avoiding the usage of arguments to create access to them?

Daniel Bandeira
  • 360
  • 1
  • 2
  • 12

1 Answers1

-1

You can use the keyword self to indicate the method of the object itself

class W:
   def r():  return 3
   def rr(self): return 2 + self.r()
   y = r()
   x = rr(r)
  • There are a few things wrong with this - 1. It doesn't work. You pass `r` as the `self` argument to `rr`, but the function `r` doesn't have an `r` attribute so `self.r()` throws an AttributeError. 2. The class `W` isn't defined yet, so it can't be instantiated. There's no point passing `self` to `rr`, because there _is no `self` to pass` when you call it in `x = rr(...)` – Pranav Hosangadi Dec 07 '22 at 18:37
  • Also, `self` isn't a keyword: https://stackoverflow.com/q/2709821/2745495 – Gino Mempin Dec 11 '22 at 06:39