0

Isn't this simpler?:

class A(self, name, age):

    def info(self):
        print('My name is', name)
        print('My age is', age)

me = A('Joe', 30)

Why do I need to do this instead?

class A:
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        print('My name is', self.name)
        print('My age is', self.age)   

me = A('Joe', 30)

Apologies in advance if this has been answered before but I couldn't find the answer and I'm new to programming.

Ben Hall
  • 87
  • 1
  • 6
  • 2
    The first method is how you do inheritance: https://docs.python.org/3/tutorial/classes.html#inheritance -- so that wouldn't due to the design of the language. – costaparas Feb 25 '21 at 12:57
  • As for the reason we "need" `__init__`, it is again because that's the way the language was designed. You can read about how `__init__` works in the [docs](https://docs.python.org/3/reference/datamodel.html#object.__init__). – costaparas Feb 25 '21 at 13:02
  • Does this answer your question? [What \_\_init\_\_ and self do in Python?](https://stackoverflow.com/questions/625083/what-init-and-self-do-in-python) – costaparas Feb 25 '21 at 13:02
  • You can't do that because it's simply not how the language works, but see e.g. https://docs.python.org/3/library/dataclasses.html for an alternative to writing everything out. – jonrsharpe Feb 25 '21 at 13:05
  • Thanks for the docs on inheritence costa, that explains it. – Ben Hall Feb 25 '21 at 13:11

1 Answers1

1

You can't Do class A(self, name, age): Because its the syntax of inheritance and we use/define __init__ because its basically constructor of a class in python

But you can do this instead:-

class A:
    def info(self,name,age):
        self.name=name
        self.age=age
        print('My name is', name)
        print('My age is', age)

me = A()
me.info('Joe', 30)
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
  • 1
    Ah, the parenthesis are reserved for something else (inheritence)! Which also explains why they're optional when creating a class. Tyvm! I haven't covered inheritance but I have just covered functions and it seemed odd you couldn't use the same syntax. – Ben Hall Feb 25 '21 at 13:10
  • when you cover topics like `inheritance` or `polymorphism` you get to know more about `__init__`..........Btw If this answer solve your problem or help you out then try consider giving an upvote or accepting answer – Anurag Dabas Feb 25 '21 at 13:20