Search code examples
pythonclassinstantiation

Python: How to inherit and display the id defined in the class, rather than have to define it in the object


I have the following Python code from a question on www.testandtrack.io:

class Sales:
  def __init__(self,id):
    self.id=id
    id=321

val=Sales(123)
print(val.id)

The output here is: 123

I want to be able to display the value of the id of the object, but for it to be what is originally defined in the class, e.g. in this case '321'. I'd like to also understand how to override (as shown) when required, but leave class default attributes in when required.

I have tried leaving it blank on instantiation, but a positional argument is required.

val=Sales()

I've also tried to remove id from the 'constructor' function like below but that doesn't work either:

def __init__(self):

Could someone point me in the right direction with an explanation? I would like every object, by default, to inherit the id (or any specified attribute) of the class rather than have to explicitly define the values on creation. When required, for certain attributes, I would want to provide new values for the object, despite the value being defined in the class. (overriding)


Solution

  • Given that 321 is the default value in case no id is passed, you should do like this

    class Sales:
       def __init__(self, id=321):
          self.id=id
    
    val = Sales(123)
    print(val.id) 
    val2 = Sales()
    print(val2.id)