0

In Python, when defining a class it's possible to use previously defined attributes in new attributes definition without any further reference.

class Parent(object):
    a_value = 'a'
    another_value = 'b'
    all_values = (a_value, another_value)

Is it possible to do the same in a derived class but still accessing some of these parent attributes?

I tried doing something like this:

class Child(Parent):
    a_child_value = 'c'
    all_values = (a_value, another_value, a_child_value)

But it seems that it doesn't take into account the Parent inheritance and gives me the following error:

NameError: name 'a_value' is not defined

So, is there any way to indicate that the a_value and another_value should be from the parent class instead of the current context?

In my case in particular the values are not strings but rather pre-compiled regular expressions, so I would like to avoid having to create them inside the __init__ method every time a new instance is created.

Carles Sala
  • 1,989
  • 1
  • 16
  • 34
  • @Moses Koledoye: I wouldn't consider this a duplicate: While the question you indicated implicitly contains the information I was looking for, what is being asked is different. I asked about "how" to do something because I couldn't find it anywhere, and that question asks about "why" it has to be done in this way. – Carles Sala Sep 29 '16 at 09:28
  • The dupe target more than answers your question. It describes in more detail what you want; why and how. The questions don't have to be exactly the same. – Moses Koledoye Sep 29 '16 at 09:35

2 Answers2

1

You need to do Parent.a_value in order to get the value you are after. a_child is a static attribute and therefore attached to the class itself and not a local variable.

class Child(Parent):
    a_child_value = 'c'
    all_values = (Parent.a_value, Parent.another_value, a_child_value)

If it is derived from something, you HAVE to type what it is derived from.

Frogboxe
  • 386
  • 4
  • 12
  • I'm afraid this is not a valid solution, since `Child` has not been yet completely defined and it doesn't exist as a valid reference. You can try yourself (which, btw, you should always do before responding any question) and see that it raises the following: `NameError: name 'Child' is not defined` – Carles Sala Sep 29 '16 at 09:14
  • Yes, you're correct, I'm very much used to abstracts not statics and that would have worked like that. I did actually test, but I only quickly put together a thing with X as the parent and Y as the child and only checked if I could get "a" attribute (that X had) from the IDE ">>>" thing (don't know the proper name for that line). – Frogboxe Sep 29 '16 at 12:44
1

like this.

class Child(Parent):

    a_child_value = 'c'

    all_values = (Parent.a_value, Parent.another_value, a_child_value)
Howardyan
  • 667
  • 1
  • 6
  • 15