8

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?

3
  • 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. Commented Feb 8, 2013 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. Commented Feb 8, 2013 at 12:23
  • My God. Attributes are static by default. Thanks for pointing this out. Commented Feb 8, 2013 at 12:38

1 Answer 1

11

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.

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

5 Comments

Um, so do you mean my first code suggestion is the correct one?
@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.
`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: 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.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.