-2
class one(object):
    b=squares

def squares(self):
    print('hi')

getting the following error:

NameError: name 'squares' is not defined

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 1
    What are you trying to do? When defining `one`, `squares` is not define, just as the message suggests. – Stephen Rauch Mar 16 '18 at 03:18
  • 1
    Class definitions are immediately evaluted. You need to define `squares` before you define `one`. – Christian Dean Mar 16 '18 at 03:18
  • 1
    `squares` is being treated as a variable name. Variable names are symbolic pointers to regions in memory. However, squares was not initiated and thus it does not point to anywhere, since it doesn't exist. You also need to put your function call into the `def __init__(self)` 'constructor'. – JahKnows Mar 16 '18 at 03:18

1 Answers1

0

This should work for you. Let me explain it. First code should go inside of methods, these methods can be combined into classes. You shouldn't place code in the class directly.

In Python when an object is instantiated the __init__(self) method is called directly. This method takes the self argument which will hold the attributes and functions available for this class. In our case, I added an attribute called self.size = 5. Then we call the squares(self) function. Notice we access it as self.function_name().

Then in that function we pass the self argument. Notice how we can access the self.size attribute from this function.

class one(object):
    def __init__(self):
        self.size = 5
        b = self.squares()

    def squares(self): 
        print('hi' + str(self.size))

o = one()

If you want a generic function not tied to your object. Then you need to define it before the class.

def squares(a): 
    return a*a 

class One(): 
    def __init__(self, a): 
        self.num = a 
        self.example()

    def example(self): 
        b=squares(self.num) 
        print(b) 

obj = One(4)
JahKnows
  • 2,618
  • 3
  • 22
  • 37