By BigBro666

2019-10-14 22:22:24 8 Comments

I learned python class today. Is it necessary to pass value to the variable through constructor? It seesm that I can define a class and pass value to the instance variable directly.

>>> class a():
        def _init_(self, food):
   = food    
>>> A =a()
>>> = 4
>>> print(


@ullas kakanadan 2019-10-14 23:33:22

Like mentioned in the answer above, you have typed incorrectly when you called the constructor. There are two underscores on either side of init __init__

What I would like to add is the reason your code was working:

  • You are creating a new attribute 'food' for the A object and assigning it with a value 4. This means for a new instance of the class the value will not be there.

    B = a() = 4 \\Error

  • If you don't define __init__ method, it by default calls the one in the base class object. That is the reason, in spite of mistyping init the code worked.

@Green Cloak Guy 2019-10-14 22:28:16

A constructor is like a normal function. You have to pass the function as many variables as it expects, but you can designate default values that make it so that you don't have to explicitly pass them:

class A():
   def __init__(self, food): = food

a = A()
# TypeError: __init__() missing 1 required positional argument: 'food'
class A():
   def __init__(self, food="default_food"): = food

a = A()
# 'default_food'

In your example, you mistyped __init__ (there are two underscores on each side, not one, so the method is never getting called).

Related Questions

Sponsored Content

9 Answered Questions

[SOLVED] Getting the class name of an instance?

20 Answered Questions

[SOLVED] Are static class variables possible in Python?

26 Answered Questions

[SOLVED] How do I pass a variable by reference?

11 Answered Questions

[SOLVED] How to access environment variable values?

10 Answered Questions

[SOLVED] Proper way to declare custom exceptions in modern Python?

12 Answered Questions

[SOLVED] Does Python have “private” variables in classes?

  • 2009-10-29 01:54:18
  • Omnipresent
  • 456446 View
  • 572 Score
  • 12 Answer
  • Tags:   python class private

22 Answered Questions

[SOLVED] Creating a singleton in Python

9 Answered Questions

[SOLVED] How to print instances of a class using print()?

Sponsored Content