7

I'm a C# developer learning python.

If I want to define a class with certain attributes, but not provide default values for the attributes, how is that done?

For example (this is my best guess of how to do it):

class Spam
    eggs = None
    cheese = None

Or, is this legal:

class Spam
    eggs
    cheese

Or something else?

David
  • 15,750
  • 22
  • 90
  • 150
  • 1
    Out of the 2 choices you provide, the first is legal, but not neccessary. Unless the attributes are used, there is no need to define them. Python dynamically creates attributes. – Dhara Feb 08 '13 at 12:14
  • 1
    @David: depending on what you want to do with the variables, you might want to prepend a `self.` to them [see here](http://stackoverflow.com/a/9056994/1860757). – Francesco Montesano Feb 08 '13 at 12:23
  • My God. Attributes are static by default. Thanks for pointing this out. – David Feb 08 '13 at 12:38

1 Answers1

10

You don't. You assign to the attributes later on, or set them to None.

An attribute without a value is not an attribute. Being dynamic, it's perfectly fine to assign the attribute later on without having to declare it in the class.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Um, so do you mean my first code suggestion is the correct one? – David Feb 08 '13 at 12:13
  • @David: indeed. Or omit `eggs` and `cheese` altogether. It completely depends on what you are trying to achieve, what API your class is going to present. – Martijn Pieters Feb 08 '13 at 12:14
  • `Being dynamic, it's perfectly fine to assign the attribute later on without having to declare it in the class.' - okay, I understand that, but presumably if I predefine the attributes I benefit from code completion in my IDE? – David Feb 08 '13 at 12:14
  • @David: That depends on the IDE, but in theory, yes. I have mine set to tab-complete on any legal name defined in the current file. – Martijn Pieters Feb 08 '13 at 12:15
  • 2
    @David That can help. Setting to `None` isn't an issue unless you want to use `None` as a value. In general, defining variables you know you are going to use on the class is a good idea as it makes the code easier to understand. – Gareth Latty Feb 08 '13 at 12:15