Default value for fields

I have a problem accessing fields from an object in a python script. It basically boils down to this little piece of code:

from enum import Enum

class AbstractFoo:
    def __init__(self, foo='works', bar='nope'):
        self.foo = foo
        self.bar = bar

class Foo(Enum):
    test = AbstractFoo('bla', 'tada')

      

So when in the python console I try to access my enum item with:

Foo.test.foo

      

I expect it to print me "bla" which is the value I pass to the constructor (or at least it should print "works" which would be the default I assigned).

I really get

AttributeError: 'Foo' object has no attribute 'foo'

      

you can probably already tell that i'm pretty new to python and especially to concept objects in python (I mostly write code in Java, which might lead to some scams from my part on object behavior in python).

What I figured out is what I can do:

Foo.test.foo = 'whatever'

      

and assign the value to foo this way. But in doing so, I can also assign a value to a field that I didn't even specify in the constructor, for example:

Foo.test.noField = 'shouldn't even exist'

      

and it will work just as well that I don't understand at all.

I would be very happy for some clarification on how objects work in python and / or how I could implement class enumeration in python.

EDIT: Apparently the code behaves the way I want if I remove inheritance from the Enum.

+3


source to share


2 answers


This can be quite confusing as you literally say it test

is something and then it is no longer there. This is because it Enum

is a special class that takes all of its members and "converts" them to an instance of the class. Thus, the type is test

no longer AbstractFoo

, but instead Foo

. However, you can return the original value assigned to the enum instance using the property value

:



from enum import Enum

class AbstractFoo:
    def __init__(self, foo='works', bar='nope'):
        self.foo = foo
        self.bar = bar

class Foo(Enum):
    test = AbstractFoo('bla', 'tada')

print(Foo.test.value.foo)

>>> bla

      

+3


source


As @jdehesa pointed out, Enum

are instances of the parent class Enum

. If you need them to be instances of some other class too, just inherit from it:

class Foo(AbstractFoo, Enum):
    test = 'bla', 'tada'

      



Please note that you no longer need to call directly AbstractFoo

.

+1


source







All Articles