class one(object):
b=squares
def squares(self):
print('hi')
getting the following error:
NameError: name 'squares' is not defined
class one(object):
b=squares
def squares(self):
print('hi')
getting the following error:
NameError: name 'squares' is not defined
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)