AttributeError: 'Cal' object has no attribute 'area'

class Cal(object):
    pi = 3.142

    def __init__(self, radius):
        self.radius = radius

        def area():
            return self.pi * (self.radius**2)


a = Cal(32)
a. area()

i get error when i run==== Traceback (most recent call last): File "K:/Py Projects/mini/prac.py", line 12, in a. area(32) AttributeError: 'Cal' object has no attribute 'area'

Upvotes: 0

Views: 531

Answers (2)

Pablo Paglilla
Pablo Paglilla

Reputation: 366

First, you defined area() inside of __init__(). That makes area() only accessible from there. Make sure you put it at the class level.

On top of that, you haven´t provided the self parameter in area(). That way, you are not able to access self it from within the method.

The corrected code would be:

class Cal(object):
    pi = 3.142

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return self.pi * (self.radius**2)


a = Cal(32)
a. area()

Upvotes: 1

Dun Peal
Dun Peal

Reputation: 17679

You defined the area() function inside your initializer (__init__()) function, which makes it a local function in that scope rather than a method of Cal.

Put it outside.

EDIT: you also need to add self as an argument for area().

Upvotes: 1

Related Questions