0

I've been stuck on this for a while. I cannot access the value of an object's attribute once constructed, but console prints the names just fine. The names and number of attributes needs to be dynamic and change depending on what source they come from. Therefore I can't just use a consistent way.

starting_list = ["Comapny", "Contact Name", "Email", "Phone", "URL", "Country", "Source"]

class NewClass(object):
    _myattrib = None

    def __setattr__(self, prop, val):
        super().__setattr__('myattrib', val)
        print("setting myattrib")

    def __init__(self):
        for item in starting_list:
            #cleaning up a bit
            item = str(item)
            item = item.lower()
            item = item.strip()
            item = item.replace(' ', '_')
            self.__setattr__(self, item, 'hi')
            print(item) #it reads it here

print(NewClass.url)

any help would be apprecieated.

4
  • 1
    Well, you've written your __setattr__() method to always set the attribute myattrib rather than using the actual attribute name, so I presume it's doing what you told it to. Commented Jan 5, 2018 at 21:11
  • 1
    Normally, __setattr__() isn't called directly. Also, the way you're calling it looks like it would raise an error. Try setattr(self, name, value). Also, str(item) doesn't do anything useful. Commented Jan 5, 2018 at 21:11
  • I'm more interested in your reasoning behind needing dynamic attributes. I'd bet it's unnecessary. Commented Jan 5, 2018 at 21:34
  • i want to be able to use different csv inputs and preserve the data but add to it new data. I'd have to edit the script to include the headers of each csv. Commented Jan 6, 2018 at 17:08

1 Answer 1

1

I would update the objects __dict__ attribute instead of messing around with __setattr__

class NewClass:
  def __init__(self, items=(), default='hi'):
    sanitized = (str(item).lower().strip().replace(' ', '_') for item in items)
    self.__dict__.update({item: default for item in sanitized})

starting_list = ["Comapny", "Contact Name", "Email", "Phone", "URL", "Country", "Source"]

nc = NewClass(starting_list)

print(nc.email) # prints hi

Edit: split some lines up for readability

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

1 Comment

ahhhh. Thanks. I tried dict.fromkeys() but didnt think to update the self.__dict__. Thanks a million

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.