0

sorry about the novice question, but im fairly new to programming. my question is, when inheriting more attributes from a parent class than I need, how can I set one of those attributes equal to another one? heres an example:

class numbers():
     def __init__(self, x, y, z):
     # x, y and z initialized here

class new_numbers(numbers):
     def __init__(self, x, y):
        numbers.__init__(self, x, y=x, z)
        # what im trying to do is get the y attribute in the subclass to be equal to the x attribute, so that when the user is prompted, they enter the x and z values only.

Thanks for your help!

nameless
  • 1,969
  • 11
  • 34
peppy
  • 407
  • 2
  • 7
  • 14
  • 1
    All your classes should extend `object` and use `super` for calling the super constructor and/or other parent functions. See http://stackoverflow.com/questions/4015417/python-class-inherits-object – bikeshedder Jan 30 '13 at 00:08

2 Answers2

2

You need something like this:

class numbers(object):
    def __init__(self,x,y,z):
        # numbers initialisation code

class new_numbers(numbers):
    def __init__(self,x,z):
        super(new_numbers,self).__init__(x,x,z)
        # new_numbers initialisation code (if any)
isedev
  • 18,848
  • 3
  • 60
  • 59
  • is there a way to do it without using super? although it does work, so thank you! – peppy Jan 29 '13 at 23:54
  • `super(new_numbers, self).__init__(x, x, z)` is more or less an alias for `numbers.__init__(self, x, x, z)`. Using `super` is recommended though as it also takes care of calling the proper constructors when inheriting from more than one class. – bikeshedder Jan 29 '13 at 23:57
  • See nameless's answer. The issue with not using `super` is that you are hard-coding the initialisation path, which could change if you change your class definitions and you overlook the hard-coding when/if you do. – isedev Jan 29 '13 at 23:59
  • `super` only works for new style classes. For this code to work the numbers class must extend `object`. – bikeshedder Jan 30 '13 at 00:03
0

Did you mean something like this?

class numbers():
     def __init__(self, x, y, z):
         # x, y and z initialized here

class new_numbers(numbers):
     def __init__(self, x, z):
        numbers.__init__(self, x, x, z)

You can't use non-keyword arguments after keywords in function/method call.

nameless
  • 1,969
  • 11
  • 34
  • yes thank you! i don't know why i didn't try that. I kept doing something like: numbers.__init__(x, y=x, z) which never worked. i assumed it would work the same way as if I set an attribute equal to a number. guess i was wrong. thanks! – peppy Jan 30 '13 at 00:01
  • @peppy, the better style is to use `super` though, as @isedev suggested. – nameless Jan 30 '13 at 00:06