-1

If we have the following code:

class Dog:
      breed = "Hamster"
      color = "Blue"
      .... tons of properties ...
      favoriteLanguage= "Python"

In another script, we don't realize that Dog class already has favoriteLanguage, we might do something by accident:

luna = Dog() luna.favoriteLanguage = "C++"

We supposed to keep favoriteLanguage as a public variable, a const or something cannot be modified like that, because it might cause hidden bug. The best way is to get error/warning to notice this. How can we do this in Python?

Huy H Nguyen
  • 11
  • 1
  • 5

1 Answers1

0

You can define a setter method.

@property
def favoriteLanguage(self):
    return self.__favoriteLanguage

@table_name.setter
def favoriteLanguage(self, favorite_language):
    if not self.favoriteLanguage:
        self.__favoriteLanguage = favorite_language
    else:
        raise AttributeError
pissall
  • 7,109
  • 2
  • 25
  • 45