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)
CodePudding user response:
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)
CodePudding user response:
class Sales:
def __init__(self,id):
self.id=id
self.id=321
val=Sales(123)
print(val.id)
And the output will be 321
To edit the id of Sales, you have to put self. before. Python is strict about it
CodePudding user response:
Ok , I didn't understand the question sorry.
Here is a way to do what you want to do :
class Sales:
def __init__(self):
pass
def set_id(self,id):
self.id=id
val=Sales()
val.set_id(100)
print(val.id)
The answer will be 100
class Sales:
def __init__(self):
pass
def set_id(self,id):
self.id=id
val=Sales()
val.set_id(100)
val.set_id(200)
print(val.id)
And for this one it will be 200