Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare an attribute in Python without a value?

Tags:

python

class

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?

like image 931
Sergio Tapia Avatar asked Jan 19 '10 15:01

Sergio Tapia


People also ask

How do you declare a variable without a value in Python?

Use the None Keyword to Declare a Variable Without Value in Python. Python is dynamic, so one does not require to declare variables, and they exist automatically in the first scope where they are assigned. Only a regular assignment statement is required. The None is a special object of type NoneType .

How do you declare an int variable without a value in Python?

In Python, sometimes it makes sense to declare a variable and not assign a value. To declare a variable without a value in Python, use the value “None”.


1 Answers

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 
like image 140
Kenan Banks Avatar answered Nov 15 '22 18:11

Kenan Banks