Error trying to set the value of a class property

Asked

Viewed 45 times

-1

I’m a beginner in Python and I’m trying. I’m trying to understand the classes by creating some instances, but I get an error:

Traceback (most recent call last)
  File "main.py", line 24, in <module> 
    f1.name = "Jose"
  File "main.py", line 19, in set_name
    self.name = n
  File "main.py", line 19, in set_name
    self.name = n
  File "main.py", line 19, in set_name
    self.name = n
  [Previous line repeated 495 more times]
  File "main.py", line 18, in set_name
    if self.checkInvalidChars(n) == True:
  File "main.py", line 6, in checkInvalidChars

My code:

    class Employee(): 
      def __init__(self):
        self._name = ""

      def checkInvalidChars(self, string):
        _invalid = str.split("! @ # $ % ¨ & * ( ) - + = [ { ? / ° < > , : ; | \ 1 2 3 4 5 6 7 8 9 ª ")
        for j in list(string):
          if (j in _invalid == True) and (isinstance(string, str) == False):
            return False
          return True
      def get_name(self):
        if self._name != "":
          return self.name
        else:
          print("The name is not registred")

      def set_name(self, n):
        if self.checkInvalidChars(n) == True:
          self.name = n

      name = property(fget = get_name, fset = set_name)

    f1 = Employee()
    f1.name = "Jose"

    print(f1.name)
  • I Suggest you read the community guidelines for Doing a good! Questions in English you should Ask in the community Where your Native language is in stackoverflow!

  • What do you mean, man?? You’re giving José an input and you come to cheat me with English? Translate here that we help you.

  • 1

    You’re making self.name = n inside set_name, which is the Setter of the name; by doing this you create an infinite loop. It should not be self._name = n?

1 answer

0

You are defining infinite recursion in the two methods of your property.

def get_name(self):
  if self._name != "":
    return self.name
  else:
    print("The name is not registred")

You did return self.name, but self.name is a property you defined by:

name = property(fget = get_name, fset = set_name)

That is, the value returned in return self.name will be the value returned by get_name, but this is being run within itself get_name, which ends up generating an infinite recursion. Within the methods getter, Setter and Deleter of a property you cannot work with the property itself; instead you will work directly on the attribute that is used by it, in this case the self._name.

Then the right thing would be:

def get_name(self):
  if self._name != "":
    return self._name
  else:
    print("The name is not registred")

The same goes for the Setter when it does self.name = n, calling his own Setter; then:

def set_name(self, n):
  if self.checkInvalidChars(n) == True:
    self._name = n

Browser other questions tagged

You are not signed in. Login or sign up in order to post.