简体   繁体   中英

Why is that i have to give argument while accessing print(dir(instance.function('hello'))) in our object in python?

lets consider the below mentioned example

class car():
    def car_type(self,car_name):
        return f'its an electric car and its a {car_name}'
instance=car()
print(instance.car_type('BMW'))
print(dir(car()))
print(dir(instance.car_type('hello')))

when you look closely to above mentioned code you will find that i have tried to access the directory of instance.car_type using this statement print(dir(instance.car_type('hello'))) and for instance if you remove the 'hello' from this statement it will thrown an error

TypeError: car_type() missing 1 required positional argument: 'car_name'

so in order to avoid this error i first tough it will take the same argument 'BMW' which i used earlier while calling the method of this class and error went away and when i tried changing 'BMW' argument with any random word for example 'hello' error went away but why that happened is still unknown to me.

and what surprised me most was that when i didn't gave any variable to my car_type function as mentioned below i was still able to access the directory of instance.car_type without any argument.

class car():
    def car_type(self):
        return 'its an electric car and its a'
instance=car()
print(instance.car_type())
print(dir(car()))
print(dir(instance.car_type()))

If you don't give argument, compiler won't be able to compile code.

car_name parameter: def car_type(self,car_name) needs its argument in calling method: instance.car_type(???)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM