2

I am new to python ( coming from Java world ). I have a class which has two attributes. I need another attribute which should be an object.

How can I do that more in a pythonic way?

This is what I have tried

class DummyData():
    def __init__(self,lat,long):
        self.lat = lat
        self.long = long
        self.data = []
loc_1 = DummyData(12,22)
my_data = {
    "mess_11" : 0.002,
    "mess_22" : 2.222,
    "mess_33" : 3.23

}

loc_1.data = my_data
7
  • are you asking about init parameters? Can you try to clarify your question? Commented Apr 27, 2018 at 12:08
  • DummyData.data is created as list, however, you are assigning dictionary (Java map) into it. Are you sure this is what you want? Commented Apr 27, 2018 at 12:08
  • Please dont use () as it would make any sense. The contents of () for the class is used for inheritance. Commented Apr 27, 2018 at 12:09
  • to clarify @What comment, don't use () after the class name Commented Apr 27, 2018 at 12:10
  • @What dont know what you meant Commented Apr 27, 2018 at 12:27

1 Answer 1

2

Do you want keyword args?

class DummyData:
    def __init__(self,lat,long,**kwargs):
        self.lat = lat
        self.long = long
        self.data = kwargs

loc_1 = DummyData(12,22,mess_11=0.002,mess_22=2.222,mess_33=3.23)
print(loc_1.data['mess_11']) # 0.002

or just a dict argument?

class DummyData:
    def __init__(self,lat,long,dct):
        self.lat = lat
        self.long = long
        self.data = dct

loc_1 = DummyData(12,22,{
    "mess_11" : 0.002,
    "mess_22" : 2.222,
    "mess_33" : 3.23
})
print(loc_1.data['mess_11']) # 0.002

or what else?

class DummyData:
    def __init__(self,lat,long,dct):
        self.lat = lat
        self.long = long
        self.data = type('myobj', (), dct)

loc_1 = DummyData(12,22,{
    "mess_11" : 0.002,
    "mess_22" : 2.222,
    "mess_33" : 3.23
})
print(loc_1.data.mess_11) # 0.002
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.