0

I am curious to know can we define a variable without initialising it.

class A:
  a

obj=A()
obj.a=8 

It throw NameError: name 'a' is not defined

Although i have defined variable a , but haven't initialised. Out of static/class variable and instance variable scope i want to know this, as i am learning python

aniketpant
  • 113
  • 1
  • 8
  • 4
    No, in Python you initialise a variable by giving it value. So just remove the `a` in class definition and it will work. – matszwecja Mar 09 '23 at 08:46
  • 1
    Variables must have a value; the "uninitalized" concept does not exist in Python. The "no value" value is `None`. – molbdnilo Mar 09 '23 at 08:47
  • 2
    Why would you want this? Are you particularly fond of the mysterious bugs it causes? – molbdnilo Mar 09 '23 at 08:50
  • Hi @molbdnilo i actually not aware of uninitialised concept does not exist in , yes if i assign `None` to variable `a` then it is working. – aniketpant Mar 09 '23 at 09:06
  • Does this answer your question? [Class (static) variables and methods](https://stackoverflow.com/questions/68645/class-static-variables-and-methods) – Tzane Mar 09 '23 at 09:08
  • No , i checked this post already. – aniketpant Mar 09 '23 at 09:16
  • @aniketpant if you assign `None` to a variable... then that variable is initialized. In any case, as others have pointed out, there really is no concept of "uninitialized variable" in Python. – juanpa.arrivillaga Mar 09 '23 at 09:27
  • 1
    "Although i have defined variable a" No, no you haven't. Hence why the interpreter is *telling you* it is undefined. – juanpa.arrivillaga Mar 09 '23 at 09:27
  • So you mean defining and initialising both are different in python. Under class A variable 'a' is there. – aniketpant Mar 09 '23 at 14:59
  • @aniketpant I think you're missing the point. (Are you perhaps familiar with C or C++?) The idea of "defining" or "initializing" variables does not exist. A variable is created, in the current scope, when you first assign it a value - that is, `a = some_value` is the *only* way to create a variable `a`. You can't create a variable that has no specific value and assign it a value later. (And this is a good thing.) – molbdnilo Mar 09 '23 at 15:22
  • Thank you @molbdnilo , i learnt c/c++ programming language 4 years ago now i forget all the things so i am starting with python . – aniketpant Mar 10 '23 at 05:57

0 Answers0