Home > other >  setting self variables based on each other
setting self variables based on each other

Time:09-17

quick question in python let's say my class goes like this

class Enemy():
   def __init__(self, level):
      self.level = level
      self.damage = self.level   5

the thing is that since the self.damage value is instantiated once it will not update when self.level is changed, how can I make it do just that? I tried searching online but I have no idea what this is called so I cannot find any help

CodePudding user response:

You can use properties. Maybe you know getter and setter methods from other programming languages. Properties are the Python equivalent of them. In this case, you only need a getter method.

class Enemy():
   def __init__(self, level):
      self.level = level

   @property
   def damage(self):
      return self.level   5

The beauty is, you can still access damage as an attribute on your instance like enemy.damage, without having to explicitly call the method, it's done automatically.

CodePudding user response:

In addition to using properties, you can also make damage a function rather than a variable:

def damage():
    return self.level   5

CodePudding user response:

This is a nice article about properties:
https://www.freecodecamp.org/news/python-property-decorator/

They allow you to control how attributes are accessed, which makes it easier to update them in the future if you decide a change in needed. For example, instead of being a flat 5, you can change the value or make it variable and anything that calls the attribute will not be affected.

Later you can add a way of manually setting the damage if you wanted to, through the use of @damage.setter.

class Enemy():
  '''This holds the data and functionality for enemies'''

  def __init__(self, level):
    self.level = level
    # Show the damage being set
    print(self.damage)

  @property
  def damage(self):
    return self.level   5
  • Related