1

I have this code:

class GameChar:
    def __init__(self, name, health, level):
        self.name = name
        self.health = health
        self.level = level

    def speak(self):
        print('Him ,my name is: '+self.name)


class Villain(GameChar):
    def kill(self, person):
        print("I will kill "+person.name)
        person.health = 0
        print("You are dead")


Mathew = GameChar("Mathew", 300, 25)

Hell = Villain("Hell", 1000, 100)
Hell.kill(Mathew)

print (Mathew.health)

I get why we need self in the constructor or in methods that are somehow using class element's data, but why do i need self if I'm only performing operation on element of another class. Why do I need a link on myself in this instance?

Is there any point of using bytecode to understand this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
nachtblume
  • 57
  • 5
  • 4
    if you don't need self (your method is static) you can use the `@staticmethod` decorator. take a look at https://docs.python.org/3/library/functions.html#staticmethod –  Apr 05 '22 at 16:29
  • Where did you get the idea that bytecode was related to this? – Scott Hunter Apr 05 '22 at 16:31
  • Python has no idea whether the method is going to use its `self` parameter or not. It gets passed unconditionally. – jasonharper Apr 05 '22 at 16:31
  • @ScottHunter I would assume they mean that they want to look at the bytecode output to see what happens in a function with an unused self parameter, versus a function without a self parameter, or one in which it is used. – Random Davis Apr 05 '22 at 16:32
  • So in this case i'd better be using @staticmethod def kill(person) ? Is it a good way of writing code ? – nachtblume Apr 05 '22 at 16:33
  • @ScottHunter TY, that's exactly what i meant – nachtblume Apr 05 '22 at 16:34
  • "Good" gets into the subjective, but my personal suggestion is as follows. What's the usage mechanism? If you expect someone to call `YourClass.your_static_method(...args...)`, I'd declare it a `@staticmethod`. By contrast, if you expect it to be called with `instance_of_your_class.your_static_method(...args...)`, I'd just accept a `self` even if you don't use it. The point is that when you declare a method static explicitly, you're promising it'll _continue_ to not need an instance even in future versions of your API, so you're constraining what you can do in the future. – Charles Duffy Apr 05 '22 at 16:34
  • Having a `self` parameter to `.kill()` makes sense, even if you're not currently using it - the next version of `Villain` might want to deliver a lengthy monologue that includes their name, for example. – jasonharper Apr 05 '22 at 16:37
  • Well guys i really understod it rn. Thank you so much! – nachtblume Apr 05 '22 at 16:40

0 Answers0