Define and call plus_2_times_4 with self, namely:
class ExampleClass():
def __init__(self, number):
self.number = number
def plus_2_times_4(self,x):
return(4*(x + 2))
def arithmetic(self):
return(self.plus_2_times_4(self.number))
This will work.
Answer from muskrat on Stack OverflowDefine and call plus_2_times_4 with self, namely:
class ExampleClass():
def __init__(self, number):
self.number = number
def plus_2_times_4(self,x):
return(4*(x + 2))
def arithmetic(self):
return(self.plus_2_times_4(self.number))
This will work.
Call the method using ExampleClass.plus_2_times_4:
class ExampleClass():
def __init__(self, number):
self.number = number
def plus_2_times_4(x):
return(4*(x + 2))
def arithmetic(self):
return(ExampleClass.plus_2_times_4(self.number))
Alternatively, use the @staticmethod decorator and call the method using the normal method calling syntax:
class ExampleClass():
def __init__(self, number):
self.number = number
@staticmethod
def plus_2_times_4(x):
return(4*(x + 2))
def arithmetic(self):
return(self.plus_2_times_4(self.number))
The @staticmethod decorator ensures that self will never be implicitly passed in, like it normally is for methods.
Call a function inside of a function inside of a class in Python - Stack Overflow
Defining class functions inside class functions: Python - Stack Overflow
Class definition within function
python - Creating a class within a function and access a function defined in the containing function's scope - Stack Overflow
Updated after question edit:
Check out this link that shows how to make a "closure" https://stackoverflow.com/a/4831750/2459730
It's what you described as a function inside of a function.
def run(self):
def calculate(self): # <------ Need to declare the function before calling
return self.number**2
print "I will now square your number"
print "Your number squared is: "
print self.calculate() # <---- Call after the function is declared
Before question edit:
Your calculate function isn't indented properly.
def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()
#This squares the number
def calculate(self): # <----- Proper indentation
return self.number**2 # <------ Proper indentation
The calculate function should have the same indentation level as the run function.
Indentation level is off. You are defining calculate INSIDE of the run function instead of in the class.
class Foo(object):
def __init__(self, number):
self.number = number
def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()
#This squares the number
def calculate(self): #NOTE THE INDENTATION DIFFERENCE
return self.number**2
if __name__ == "__main__":
test = Foo(input("Choose a number: "))
print test.run()
This really depends on what you want to do.
>>> class Foo(object):
... def haha(self):
... print 3
... def __init__(self):
... def haha():
... print 4
... self.haha = haha
...
>>> a = Foo()
>>> a.haha
<function haha at 0x7f4539e25aa0>
>>> a.haha()
4
In the previous example, haha isn't actually a method -- It's just a function. But it will pick up a reference to self from the closure and a lot of the time, that's probably good enough. If you actually want to monkeypatch/duck punch a new method on an instance, you'll need to use types.MethodType. See here for an example.
This will add a method to a class from an instance. In most cases not the thing you want to do, but the language makes it just that simple.
class A(object):
def __init__(self):
def foo(self):
print "bar"
self.__class__.foo = foo
The use of such a trick can be justified when you build some kind of data-driven self-modifying code (not a every day case for most of us)
I have a class which accesses variables defined within a main() function. I know it is conventional to define classes and functions in the global scope so I moved the class out of the function, however the nonlocal keyword doesnt work if the class isnt in the function.
def main():
gv: int = 0
class myClass:
def accessGV():
nonlocal gv
doSomething(gv)
Should I move the class outside main() ? If so, should I move gv: int to the global scope?
If I keep everything in main, what happens when main is called again? Does the class get defined again and take up lots of memory?
That's an artifact of Python's name resolution rules: you only have access to the global and the local scopes, but not to the scopes in-between, e.g. not to your immediate outer scope.
EDIT: The above was poorly worded, you do have access to the variables defined in outer scopes, but by doing x = x or mymethod = mymethod from a non-global namespace, you're actually masking the outer variable with the one you're defining locally.
In example 2, your immediate outer scope is the global scope, so MyClass can see mymethod, but in example 4 your immediate outer scope is my_defining_func(), so it can't, because the outer definition of mymethod is already masked by its local definition.
See PEP 3104 for more details about nonlocal name resolution.
Also note that, for the reasons explained above, I can't get example 3 to run under either Python 2.6.5 or 3.1.2:
>>> def myfunc():
... x = 3
... class MyClass(object):
... x = x
... return MyClass
...
>>> myfunc().x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in myfunc
File "<stdin>", line 4, in MyClass
NameError: name 'x' is not defined
But the following would work:
>>> def myfunc():
... x = 3
... class MyClass(object):
... y = x
... return MyClass
...
>>> myfunc().y
3
This post is a few years old, but it is among the rare ones to discuss the important problem of scope and static binding in Python. However, there is an important misunderstanding of the author for example 3 that might confuse readers. (do not take as granted that the other ones are all correct, it is just that I only looked at the issues raised by example 3 in details). Let me clarify what happened.
In example 3
def myfunc():
x = 3
class MyClass(object):
x = x
return MyClass
>>> myfunc().x
must return an error, unlike what the author of the post said. I believe that he missed the error because in example 1 x was assigned to 3 in the global scope. Thus a wrong understanding of what happened.
The explanation is extensively described in this post How references to variables are resolved in Python
Since these are member functions, call it as a member function on the instance, self.
def isNear(self, p):
self.distToPoint(p)
...
That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).
I'm learning to work with classes and I'm trying to turn my procedural code that's working perfectly into a class with a series of functions (def) within. I ran into an error while testing though. It says "name def2 is not defined," and I'm not sure how to define it.
I wrote:
from <file> import Class x = Class() x.def1() x.df
So far it works perfectly and the data table looks like what I expect. def1 only uses self as a parameter.
After def1, def2-4 all use different parameters, so I can't simply write x.def2 like I did above, otherwise it errors out because I didn't input a second parameter.
Then def5 is another function with only self as a parameter that is merely a series of procedural lines that call upon def2-4 written above. However, when I tried to run x.def5(), it errors out saying "def2 is not defined," and if I comment out the def2 part, it errors out saying "def3 is not defined" instead.
How do I define these functions so I can call upon them in a separate function within the same class?
Hi, folks I was always wondering why certain modules would have almost every single one of their functions inside a class. What are some example benefits?
Thanks in advance.
If you had read the error message from the first example then that might have given you a clue.
self.tooAhg=self.oaf(self.ahg)
AttributeError: foo instance has no attribute 'oaf'
The function name is oaf, not self.oaf.
class foo:
def __init__(self,ahg):
self.ahg=ahg
def oaf(arg):
return arg*2
self.tooAhg=oaf(self.ahg)
bibi=foo(1)
print vars(bibi)
Gives:
{'tooAhg': 2, 'ahg': 1}
If you want to make the function oaf an attribute of the object, then:
self.oaf = oaf
Not sure if this fits your use-case but if tooAhg has to be 2*ahg always, you should use properties:
class Foo(object):
def __init__(self, ahg):
self.ahg = ahg
@property
def tooAhg(self):
return 2 * self.ahg
Now, you can access tooAhg like any other class field (ex. self.tooAhg), without worrying about updating it whenever you update ahg
Using self.mode_impute is indeed the correct way of calling the function inside the class. However the issue here is that your call is not part of a function, putting the for loop with the call inside a function (e.g. __init__) should solve the error as self is defined within the function (passed as the first argument).
You can move the for loop calling the model_impute() method either to within your __init__() constructor or outside of the impute class. But I don’t see the dataset df6 defined anywhere.
So I would redesign things a bit. Create a fit_transform(X) method within your impute class. This takes in a X data frame from the user, saves it for the class instance & then populates missing values with the for loop invoking mode_impute().
It’s just that I need to use some variables from the result inside main(). Wondering if it looks bad to do that?
This code works perfectly fine.
def hi():
print("hi")
def __init__():
print("ok")
bye()
def bye():
print("bye")
hi()
__init__()
>>hi
>>ok
>>byeWhen I put it into a class, it doesn't.
class Msg:
def hi():
print("hi")
def __init__(self):
print("ok")
bye() #bye is not defined
def bye():
print("bye")
hi()
Msg()
>>hi
>>ok
>>NameError: name 'bye' is not defined on line 8
I can easily fix it by changing the bye() on line 8 with Msg.bye()
class Msg:
def hi():
print("hi")
def __init__(self):
print("ok")
Msg.bye() #solved
def bye():
print("bye")
hi()
Msg()
>>hi
>>ok
>>byeMy question:
-
Why do I have to prefix
bye()withMsg.when it is already inside the same shared class? All the functions are defined at the same indentation level, so I'm not sure whybye()isn't defined within__init__ -
If I still have to prefix functions inside a class with their classname, why DON'T I have to prefix the last calls in the class from
hi()toMsg.hi()instead?
Re Q2: (Yes, I know it doesn't work because Msg isn't defined until all the top level code is run, but the question still applies conceptually)