0

I'm quite familiar with python but I don't know much about the "pythonic" way of doing things and I would like to learn. At first I was trying to create two different constructors and I got to the option of using **kwargs where you do different things depending on what attribute you pass (or don't pass) to the constructor.

The problem I'm facing now is that it doesn't matter how I call the constructor, it always returns a copy of the first object I created.

Here is a sample code:

class MyClass():
    items = []

    def __init__(self, **kwargs):
        if 'fill' in kwargs:
            print('putting something in your class')
            self.items.append('something')

filled = MyClass(fill=True)
empty = MyClass()
another_filled = MyClass(fill=True)
another_empty = MyClass(anything=80)

print(filled)
print(empty)
print(another_filled)
print(another_empty)

print(filled.items)
print(empty.items)
print(another_filled.items)
print(another_empty.items)

And the exit:

putting something in your class
putting something in your class
<__main__.MyClass object at 0xb71b9b4c>
<__main__.MyClass object at 0xb71b9c0c>
<__main__.MyClass object at 0xb71b9c2c>
<__main__.MyClass object at 0xb71b9ccc>
['something', 'something']
['something', 'something']
['something', 'something']
['something', 'something']

I feel I'm missing something really stupid. Help, please.

SPL_Splinter
  • 483
  • 1
  • 5
  • 16

0 Answers0