+ 1
How to use arbitrary keyword argument in class instance.[python]
11 Answers
+ 7
janvi vashistha ,
it would be nice if you could give us a sample...
+ 2
Arbitrary in what way?
+ 2
If you wanted keyword-argument then it should be
def __init__( self, make, model, year, **user_profile ):
# function body
Notice there was a missing comma between argument <year> and <user_profile>. And we use double asterisks to denote keyword-argument.
At instantiation time, pass pairs of `key = value` after the first 3 arguments
car = Car( 2019, 'Audi', "A4', fuel = Petrol', displacement = 2000, engine ='I4', top_speed = 241 )
You will have a `dict` named <user_profile> inside __init__() you can check its content
+ 2
Save the most recent update and share its link here. No one can help if they can't review the code ...
Here's how to share code bit link
https://www.sololearn.com/post/75089/?ref=app
+ 2
Look at this line
long_name = ( ... )
The string is not properly formed, it's missing a single quote at its end.
Also you don't need to wrap the f-string inside parentheses
+ 1
class Car:
"""A simple attempt to represent a car."""
def __init__(self,make,model,year *user_profile):
"""Initialize attributes to describe a car."""
self.model=model
self.make=make
self.year=year
def get_descriptive_name(self):
"""Return a neatly formatted name."""
long_name=(f"{self.year} {self.make} {self.model}.")
return long_name.title()
car=Car(2019,'audi','a4')
print (car.get_descriptive_name())
+ 1
Thank you but what about self instance of user profile
+ 1
Self instance? what instance? keyword-arguments are blended into a `dict`, not an object.
Not getting what you mean ...
0
Now how to add in *user profile
0
It's not working
0
class Car:
"""A simple attempt to represent a car."""
def __init__(self,make,model,year ,**user_profile):
"""Initialize attributes to describe a car."""
self.model=model
self.make=make
self.year=year
def get_descriptive_name(self):
"""Return a neatly formatted name."""
long_name=(f'{self.year} {self.make} {self.model})
return long_name.title()
car=Car(2019,'audi','a4', fuel='petrol',speed=251)