52

In C# I would go:

string UserName;
string Password;

But now, in Python:

class User:
    UserName
    Password

I receive an error that UserName isn't defined. Can I not declare a variable without a variable?

0 _
  • 10,524
  • 11
  • 77
  • 109
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

6 Answers6

84

In Python, and many other languages, there is a value that means "no value". In Python, that value is None. So you could do something like this:

class User:
   username = None
   password = None

Those sure sound like instance variables though, and not class variables, so maybe do this:

class User(object):
    def __init__(self):
        self.username = None
        self.password = None

Note how Python assigns the None value implicitly from time to time:

def f():
    pass
g = f() # g now has the value of None
Artem Fedotov
  • 432
  • 1
  • 6
  • 21
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
  • Hi there, thanks for the answer. A couple of questions though, why do you put (object) at the end of the class name? Also, what is def __init__ ? If you have a good link that'll be great. – Sergio Tapia Jan 19 '10 at 15:45
  • @Sergio Tapia: See this: http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python – Fred Larson Jan 19 '10 at 15:47
  • 1
    extending `object` in Python is kind of a syntactic hack, though an extremely common one, that means you want to use new-style classes. If using Python 2.x, you should get in the habit of doing that. `__init__` is a python constructor. – Kenan Banks Jan 19 '10 at 15:47
  • `__init__` is Python's constructor method. It takes `self` as its first parameter, which is a reference to the object to be created, as well as a variable number of other parameters. You then construct the object by manipulating `self`. – danben Jan 19 '10 at 15:49
  • Just another quick question. Class variables will be things that only my class uses, correct, like if I have a class for DB connection, the connectionstring will only be useful for itself. But instance classes are items that you want to be available if the class is instantiated, correct? – Sergio Tapia Jan 19 '10 at 15:52
  • 2
    @SergioTapia yes. See https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables – eric Sep 22 '14 at 20:15
  • When I am using such practice (declaring object variables with None in __init__ method I get a warning from 'pydev' interpreter saying: "Statement appear to have no effect", so is it a wrong warning? – GyRo Oct 21 '18 at 12:25
  • 2
    @Triptych Python definitely doesn't assign None value "from time to time". If a function/method doesn't contain a `return` statement, then it _always_ returns `None`. I know I am ~10 years late with this comment, but maybe it'll still be useful to someone. – michcio1234 Nov 29 '21 at 16:17
16

First of all, you should rewrite like this:

class User(object):
  def __init__(self, username, password):
    self.username = username
    self.password = password

This way, username and password are instance variables instead of class variables (in your example, they are class variables -- all instance variables need to be defined in __init__ as properties of self). Then, you can initialize a User with whatever username and password you want, including None if you truly want them to have no value.

danben
  • 80,905
  • 18
  • 123
  • 145
  • 1
    And, if you think you want to "declare" an attribute, you can't. You can, however, assign `None` so that you can create an attribute. – S.Lott Jan 19 '10 at 15:44
11

Dataclasses for python 3.7+:

@dataclass
class User:
    UserName: str
    Password: str
validname
  • 1,376
  • 15
  • 22
10

In your code:

class User:
    UserName
    Password
    print(UserName, Password)

UserName and Password and print(UserName, Password) are parsed as expressions. Since they have not been assigned at this point, you get a NameError.

In Python, a variable must be defined with a assignment statement before it can be used in an expression, otherwise you get a NameError. Note that "before" here means "execution order", not "source code order". There's a bit more to it (import statements, globals, namespace hacks), but let's keep it simple here.

The idiomatic way to define a variable "without a value" is to assign it the value None.

Also, your code looks like it really wants instance members, and not class members. The idiomatic way to do it, as recognized by some static analysis tools such as pylint, is:

class User(object):
    def __init__(self):
        self.username = None
        self.password = None

Also, it is good Python style to derive all classes from "object", so you use new-style classes, and to name instance variable with the lowercase_with_underscore or initialLowerWithCaps convention. The InitialCaps style is quite universally reserved to class names.

ahuigo
  • 2,929
  • 2
  • 25
  • 45
ddaa
  • 52,890
  • 7
  • 50
  • 59
6

You can't. In Python, "Variables" are just names. A name always points ("is bound") to an object. It's convention to assign names that don't yet have a sensible value, but should be present, to None.

You might also be interested in my answer here.

Community
  • 1
  • 1
balpha
  • 50,022
  • 18
  • 110
  • 131
3

Just assign the value of None:

self.username = None

0 _
  • 10,524
  • 11
  • 77
  • 109
Lyndsey Ferguson
  • 5,306
  • 1
  • 29
  • 46