0

What's the point of creating classes and self in python? Like:

class ThisIsClass(self):
    def Func():
        self.var+=1
ThisIsClass()

Is it necessary to use them?

  • 5
    This will come clear once you learn about [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming). This applies to many languages, not just Python. – David Callanan Jul 01 '22 at 10:03
  • Hi welcome to Stack Overflow. It's not really clear what you're asking. The code you posted doesn't even make sense for Python (perhaps you meant `def Func(self):`?) – Iguananaut Jul 01 '22 at 10:03
  • This is why I'm asking for what it uses, because I don't know how to use slef and classes. – GamerTronky Jul 01 '22 at 10:04
  • 2
    Welcome to Stack Overflow. Does https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self answer your question? In the future, [please try](https://meta.stackoverflow.com/questions/261592) to look for existing answers before posting. I can [literally copy and paste your question title into a search engine](https://duckduckgo.com/?q=What%27s+the+point+of+creating+classes+and+self+in+python%3F) and get lots of useful information. Someone else please close this, I am out of close votes for the day. – Karl Knechtel Jul 01 '22 at 10:04

2 Answers2

1

It becomes necessary to pass self argument to the functions of your class. however, your code has several problems like the initialization of var variable. You need a constructor __init__ to create the variable, after that, you will be able to modify it:

class ThisIsClass:
  def __init__(self, value=0):
    self.var = value

  def Func(self):
      self.var+=1

c = ThisIsClass()
c.Func()
print(c.var)

In the above code, the class is instantiated as an object and stored in the variable c. You can assign an initial value to var by passing an argument to the object creation, like: c = ThisIsClass(89)
Output:

1
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
1

It has to do with the right structure of programming in python. No you dont need them 100% but if you want to have a nice and clean code I would propose you to get used of them. Also when the self is declared inside the brackets after the function name, that function can retrieve (and make available) the variable (self.variable) from and to wherever inside that class.

Zuss
  • 59
  • 7