0

I have multiple classes in this project that all face the same situation that I am about to explain. To simplify things I will use one class and the details of it's specific situation.

Class

class ConnectedDevice(object):
    def __init__(self, mac_address, ip_address):
        self.mac_address = mac_address
        self.ip_address = ip_address

Way To Go About This # 1

I could construct instances with the member variables filled via parameters of the constructor.

This would be done by having separate functions outside of the class within main that get the necessary information.

def main():

    mac_address = get_mac_address()
    ip_address = get_ip_address()

    Device0 = ConnectedDevice(mac_address, ip_address)

Way To Go About This # 2

I could construct instances with None in the parameters of the constructor and use member functions after the fact to fill the member variables. Obviously, I would have defined member functions in my class to do so.

def main():

    Device0 = ConnectedDevice(None, None)

    Device0.set_mac_address()
    Device0.set_ip_address()

Question

I am asking which is the better Object Oriented way to go about this?

  • Way To Go About This # 1
  • Way to Go About this # 2
0

1 Answer 1

1

Isn't this more a matter of opinion? I'd say "Way to Go About This #2" is a bad idea because code isn't written to be used just once, and someday down the road you or someone else may want to use ConnectedDevice and may use it inadvertently in uninitialized fashion. Even when you know how it's supposed to be done, you can slip up.

Anyway, IMHO a better approach altogether is "Way to Go About This #3":

def main():

    Device0 = ConnectedDevice(get_mac_address(), get_ip_address())

...and if the constructor receives None for either argument, raise an exception. (But that's my taste.)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.