0

This is my code:

class robot:
    def __init__(givenName,givenColor):
        self.name=givenName//error
        self.color=givenColor//error
    def intro(self):
        print("my name izz "+self.name)

r1=robot();
r1.name='tom'
r1.color='red'

r2=robot();
r2.name='blue'
r2.color='blue'
r1.intro()
r2.intro()

I am getting an error in the above commented lines. I know this question has many answers on stackoverflow but none seems to work . the function calls self.color and self.color give the error.

0

1 Answer 1

2

The first argument of __init__ should be self:

def __init__(self, givenName, givenColor):
    self.name = givenName
    self.color = givenColor

Otherwise, your code will fail as self will not be accessible within the method.

You have 2 options to define attributes:

Option 1

Define at initialization with __init__ as above. For example:

r1 = robot('tom', 'red')

Option 2

Do not define at initialization, in which case these arguments must be optional:

class robot:
    def __init__(self, givenName='', givenColor=''):
        self.name=givenName
        self.color=givenColor
    def intro(self):
        print("my name izz "+self.name)

r1 = robot()

r1.givenName = 'tom'
r1.givenColor = 'red'
Sign up to request clarification or add additional context in comments.

2 Comments

Also, r1 = robot() will fail because it's expecting to receive 2 arguments, i.e. givenName and givenColor. You should be doing r1 = robot('tom', 'red') instead.
it worked. the first solution that included adding self at the beginning of the constructor worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.