1

Is there a way in PyCharm to take instance attributes

class C():
    def __init__(self, s: str):  #instance attribute
        pass

and add them as class attributes?

class C():
    s:str  # class attribute

    def __init__(self, s: str):  #instance attribute
        pass
Slazer
  • 4,750
  • 7
  • 33
  • 60
  • [this may help](https://stackoverflow.com/questions/58661996/add-all-constructor-parameters-as-instance-attributes-to-class-in-pycharm) with a little modification – sahasrara62 Sep 13 '21 at 08:20
  • Indeed what you showed in second example is not a class attribute. – S.B Sep 13 '21 at 09:04
  • @SorousHBakhtiary I think the attribute on the second line is in fact a class attribute. `A class attribute is a Python variable that belongs to a class rather than a particular object. It is shared between all the objects of this class and it is defined outside the constructor function, __init__(self,...), of the class.` dzone.com/articles/python-class-attributes-vs-instance-attributes `A Python class attribute is an attribute of the class (circular, I know), rather than an attribute of an instance of a class.` toptal.com/python/python-class-attributes-an-overly-thorough-guide – Slazer Sep 13 '21 at 09:49
  • @Slazer `s` is only a class attribute when you assign something to it in the body of the class. But now that you only annotated `s`, it is not a class attribute. By specifying `s: str` you're saying that instance variable `s` inside `__init__` and `__new__` should be of type `str`. [link](https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations). – S.B Sep 13 '21 at 10:07
  • @Slazer first define a class like : `class A: s:str` then try to access it's `s` attribute using `A.s` python says : _AttributeError: type object 'A' has no attribute 's'_ – S.B Sep 13 '21 at 10:10

0 Answers0