1

I dont know how to limit the values of a class attribute in python, so is it a good practise limit the values with a set function?

class Example:
   def __init__(self,name):
      self._setName(name)

   def _setName(self,name):
      if isinstance(name,str):
            self.name = name
ymd_
  • 189
  • 15
  • 1
    BTW, `self.name` is an _instance_ attribute, not a _class_ attribute. See http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes – PM 2Ring Dec 16 '16 at 12:40
  • 2
    I don't quite agree with the marking as duplicate because the main question is about the good practice. I think it is possible but it is not good practice in general, although it has been systematized in some frameworks. It's a lot more code for very little benefit. The exceptions system is sufficiently efficient to identify type errors in almost all cases. – Gribouillis Dec 16 '16 at 13:11
  • If you want a class attribute then use Example.name rather than self.name. Or you can use a `@classmethod` or `@staticmethod` decorator and use `cls.name` to access it. If you can use Python 3.5, it supports a static type checking. Just include `from typing import Text` on the top and put `def __init__(self, name: Text):` on your dunder init function. Also, If you haven't already I highly encourage you to use a proper IDE like PyCharm because it helps you to follow the PEP 8 coding standards. Remember 4 spaces instead 3 and the function name should be in all lower case. – Eddie Dec 16 '16 at 14:20

0 Answers0