ravi tanwar
ravi tanwar

Reputation: 618

Unresolved reference in Python class

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.

Upvotes: 0

Views: 3322

Answers (1)

jpp
jpp

Reputation: 164623

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'

Upvotes: 2

Related Questions