How to use arbitrary keyword argument in class instance.[python] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to use arbitrary keyword argument in class instance.[python]

28th Nov 2022, 12:01 PM
janvi vashistha
11 Answers
+ 7
janvi vashistha , it would be nice if you could give us a sample...
28th Nov 2022, 4:29 PM
Lothar
Lothar - avatar
+ 2
Arbitrary in what way?
28th Nov 2022, 3:14 PM
Ipang
+ 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
29th Nov 2022, 8:57 AM
Ipang
+ 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
30th Nov 2022, 2:59 PM
Ipang
+ 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
30th Nov 2022, 3:14 PM
Ipang
+ 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())
29th Nov 2022, 7:33 AM
janvi vashistha
+ 1
Thank you but what about self instance of user profile
30th Nov 2022, 1:49 PM
janvi vashistha
+ 1
Self instance? what instance? keyword-arguments are blended into a `dict`, not an object. Not getting what you mean ...
30th Nov 2022, 2:47 PM
Ipang
0
Now how to add in *user profile
29th Nov 2022, 7:33 AM
janvi vashistha
0
It's not working
30th Nov 2022, 2:56 PM
janvi vashistha
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)
30th Nov 2022, 3:06 PM
janvi vashistha