0

Possible Duplicate:
Python variable declaration

i'm new to python, and i wonder how to put a proper "empty" variables into classes.

For example, in C++, I can put variables like:

public class employee{
private:
int ID;
string name;
public:
.....
}

In python, how do I setup the name and the id without giving them values?? Is it something like:

class employee:
__name__
__id__
...

Also, is it possible to set the data type for each variables?

3
  • 1
    What is that you want to achieve? Commented Jan 15, 2013 at 18:54
  • 2
    In your title, you refer to "Class variables", but it seems you are actually talking about "Instance Variables". A class variable has only one value that is shared between all instances of the class, whereas an instance variable (which is what you appear to be talking about in your C code, which I believe is actually C++ code) has one value for each instance of the class that you create. Commented Jan 15, 2013 at 18:54
  • @ Mark I didnt know that lol...And yes it should be c++. Thanks for pointing that out Commented Jan 15, 2013 at 19:29

2 Answers 2

2

It's true that you can't really do that, but here's what you can do:

class FooBar:
    def __init__(self):
        self.whatever = None

Also, no need to declare datatypes in Python. That's the whole point of a dynamic language!

Don't write python with a C++ accent. Write python the way it was designed and you'll be a lot happier.

Sign up to request clarification or add additional context in comments.

4 Comments

Of course Python has datatypes, lots of them. That's the whole point of strongly-typed languages! (Variables don't have types though - only objects do.)
Well - there are datatypes - it just happens to be the object that is the type, rather than the name of it... - python is strongly typed, just not statically typed :)
If there are no datatypes, we should really rename the TypeError exception ;)
I stand correctly corrected :) I'll fix
0

You can't.

There's no concept of empty variables in python, they must be initialized to something. And there's no concept of data type either. In python variable names are just symbols pointing to an object(Objects have types though).

In [37]: x=2      #x refers to an integer

In [38]: x="foo"  #now x refers to a string object

The closest thing to empty variable is to use None or Ellipsis(py 3x only)

In [5]: x=None

In [6]: x

In [7]: x=...        # Ellipsis , py 3.x only

In [8]: x
Out[8]: Ellipsis

But again None and Ellipsis are Objects themselves.

2 Comments

None is how we say "empty" in Python (but it is a real object too).
Another alternative is not to worry about missing attributes, and define __getattr__ on the class, which would return a default value - but since we don't really know what the OP wants...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.