Python Class Design – How to Structure a Class in Python

designpython

I have come to python from C++ (I also know a little Java). I am writing code to exercise a server so I basically use http methods to send a load of requests to the server. As part of my code I created a class and called it testdata. This contains basically test input data (to send in requests) and output data to check against.

With my C++ hat on I created a load of getter and setter methods which were one lines. I even had an __init__ method to set eg self.<some_attribute_name> = "" or some safe default.

I realise now that you can freely add attributes to a python object and there is no need to pre-initialise simple variables in init.

So I have some questions.

  1. For my testdata class, should I even be using a class?

  2. I just add data items like this:

    import testing
    
    td = testing.testdata()
    td.sessionid = "123"
    
  3. But what about access eg to td.sessionid before I have previously assigned a value. I know I can use hasattr but that is an extra burden. Do I have to make sure I always assign first? What if I do td.sessionid before it is even assigned anything? I will get an AttributeError at runtime. How to handle this?

  4. Due to problem 3. above. Should I always use __init__ to initialise member data to safe default values? eg "" for strings.

What are recommended approaches in Python?

Best Answer

Generally, you use class attributes to provide defaults:

class TestData(object):
    sessionid = None

You only need to define a __init__ if you need to provide a new instance with attributes that have to be uniquely set for that new instance.

However, don't define a class just to hold state. Use classes when you are going to provide both state and behaviour. Python's standard types and library is otherwise more than rich enough to cover the just-data needs.

Related Topic