2

I'm looking for feature in pycharm that generate auto setter and getter function for each property(field) and generate auto contractor.

For example,

class A:
  def __init__(self, a, b, c, d):
      self._a = a
      self._b = b
      self._c = c
      self._d = d
  def set(self, a):
      self._a = a
  def get(self, a):
      return a
Alex
  • 33
  • 6

1 Answers1

3

This is an old question but, I came across it and would like to help any future visitors out.

PyCharm has Live Templates that you can configure for this sort of thing. But...

This will probably not exist in PyCharm as getters and setters aren't considered Pythonic and aren't how Python handles classes. This is a common misunderstanding for those coming from languages such as C++, Java or PHP.

The Python way of doing it is through Properties. See this SO question.

class A:
    def __init__(a):
        self._a = a

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, val):
        self._a = val

    @a.deleter
    def a(self):
        self._a = None

For access:

obj = A(12)
obj.a            # 12
obj.a = 13
obj.a            # 13
del obj.a
obj.a # None

If you want to use PyCharm for property getters / setters / and deleters there's an easy way to do it.

prop + TAB

will get you a property getter that you can type the name into

props + TAB

will get you a property setter and getter that you can type the name into

propsd + TAB

will get you a property setter/getter and deleter that you can type the name into

Hope this helps.