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):
            self.food = food    
>>> A =a()
>>> A.food = 4
>>> print(A.food)
4

2 comments

@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()

    B.food = 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):
        self.food = food

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

a = A()
print(a.food)
# '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

18 Answered Questions

[SOLVED] Are static class variables possible in Python?

22 Answered Questions

[SOLVED] Creating a singleton in Python

9 Answered Questions

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

26 Answered Questions

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

9 Answered Questions

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

11 Answered Questions

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

  • 2009-10-29 01:54:18
  • Omnipresent
  • 412838 View
  • 525 Score
  • 11 Answer
  • Tags:   python class private

9 Answered Questions

[SOLVED] How to access environment variable values?

8 Answered Questions

[SOLVED] Getting the class name of an instance?

Sponsored Content