Why is my code wrong


class Ball:

  def __init__ (self,ball_type):

    self.ball_type = ball_type

  if self.ball_type == None:

    print("ball type is regular") 

ball1 = Ball("super")

ball2 = Ball()

print(ball1.ball_type)

print(ball2.ball_type)

why over here it is wrong to put

if self.ball_type == None:

and has to be

if ball _type == None

Thanks

Are you sure you posted the code with the correct indentation?

The most important thing to understand is the difference between self.ball_type and ball_type.

self.ball_type is the instance variable, while ball_type is a local variable. I would do validation first, so then you need to use ball_type give the instance variable hasn’t been defined yet

looking at the method:


  def __init__ (self,ball_type):

the ball_type parameter is required parameter (without a default value), so this:


ball2 = Ball()

won’t work, the argument for the required parameter is missing

what l want is that if no parameter is provided it says its a regular ball,

so because the instance variable is not defined l have to just use ball_type, but what l was trying to do is if the instance variable is empty to print, ball type is regular

Thanks

then you need a default value/argument for your parameter.

If you give the parameter a default argument/value, you can set the instance variable to this value, and then use the parameter or instance variable to print a message

1 Like