I'm writing an program where im using two main functions however those both functions uses same inner functions. I'm wondering how I should write them in most pythonic way? My point is to hide those helpers somewhere inside and to dont repeat helper functions.
def main_function1():
helper1()
helper2()
#dowork1
def main_function2()
helper1()
helper2()
#dowork2
def helper1()
#workhelp1
def helper2()
#workhelp2
The only reasonable solution which i can figure out is declaring static class with.. private functions? But since:
Strictly speaking, private methods are accessible outside their class,
just not easily accessible. Nothing in Python is truly private[...]
Im stuck and out of ideas.
From: http://www.faqs.org/docs/diveintopython/fileinfo_private.html
Topic: Why are Python's 'private' methods not actually private?
Also I thought about declaring one main function with inner helpers and with switcher as a argument to determine which function should run but I guess thats pretty poor solution.
For now only way I find the most accurate is to declare normal class as:
class Functions:
def main_function1(self):
print("#first function#")
self.helper1()
self.helper2()
def main_function2(self):
print("#second function#")
self.helper1()
self.helper2()
def helper1(self):
print("first helper")
def helper2(self):
print("second helper")
Functions().main_function1()
Functions().main_function2()
print("###")
Functions().helper1()
Output:
#first function#
first helper
second helper
#second function#
first helper
second helper
###
first helper
But also here i can access helpers which isnt a big deal but still gives me a reason to wonder.
There are no private functions in Python. Rather, by prefixing the names of methods intended to be non-public with underscores, you signal to users of your class that those methods are not meant to be called externally:
class Functions:
def main_function1(self):
print("#first function#")
self._helper1()
self._helper2()
def main_function2(self):
print("#second function#")
self._helper1()
self._helper2()
def _helper1(self):
print("first helper")
def _helper2(self):
print("second helper")
This is in line with the principle of "We're all consenting adults here" - you can touch the non-public methods of a class, but if you use them wrongly, that's on your own head.
Try this
def get_main(name):
def helper1():
print("helper1")
def helper2():
print("helper2")
def main1():
print("Running helpers from main1")
helper1()
helper2()
def main2():
print("Running helpers from main2")
helper1()
helper2()
if name == "main1":
return main1
if name == "main2":
return main2
main1 = get_main("main1")
main2 = get_main("main2")
You can then run the function as follows:
main1()
main2()
helper1()
output:
Running helpers from main1
helper1
helper2
Running helpers from main2
helper1
helper2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'helper1' is not defined
Related
I have a little problem, I have my code below.
I want to call the "speak" function with two arguments inside the main() class.
When I call speak it says that self its not defined, and i don't know how to make it work...
Any ideas?
class main():
def blueon(self):
print("teste")
def speak(self,fala):
self.blueon
print(fala)
speak("testeaaaaa")
Try something like this.
Comments explain changes
class Main: # Class name capitalized and no parenthesis if the class has no base classs
def __init__(self): # class constructor. Initialize here your variables
pass
# if you have a function that doesn't use self, you can declare it static
#staticmethod
def blueon():
print("teste")
def speak(self, fala):
self.blueon() # added missing parenthesis
print(fala)
if __name__ == "__main__": # add this so you can later import your class as a library without executing your test code
m = Main() # instantiate the class
m.speak("testeaaaaa") # call the speak method
You run speak() in wrong way.
First you have to create instance of class m = main() and later use m.speak("text").
And you have to do with different indetation.
BTW: There is good rule to use CamelCaseName for classes - class Main(): - it helps to recognize class in code, and it allows to do main = Main().
More in PEP 8 -- Style Guide for Python Code
# --- classes ---
class Main():
def blueon(self):
print("teste")
def speak(self, fala):
self.blueon() # you forgot `()
print(fala)
# --- main ---
main = Main()
main.speak("testeaaaaa")
I am coding a simple game of tic-tac-toe. My function to check winning is too repetitive and big, so I want to put it into an external file. My idea is:
class Game(object):
def __init__(self):
pass
import funcFile
instance = Game()
instance.func()
While in funcFile.py is:
def func():
print("Hello world!")
But:
Traceback (most recent call last):
instance.func()
TypeError: 'module' object is not callable
Is there a way to do this, or should I put everything in one file?
There are many ways to solve this kind of problem.
The most straightforward solution (which is what I think you had in mind) is to factor out the implementation of the func method to a separate module. But you still need to define the method in the class.
main.py:
from func_module import func_implementation
class Game: # note: you don't need (object)
def __init__(self):
pass
def func(self):
return func_implementation()
instance = Game()
instance.func()
func_module.py:
def func_implementation():
print('hello')
Another approach would be to factor out the func method to another class which the Game class inherits. This pattern is also known as a mixin class:
main.py:
from func_module import FuncMixin
class Game(FuncMixin):
def __init__(self):
pass
instance = Game()
instance.func()
func_module.py:
class FuncMixin:
def func(self):
print('hello')
But this is less clear, as you can't immediately see that the Game class has a func method and what it does. Also you can introduce subtle bugs with multiple inheritance if you're not careful. So in your case I'd prefer the first approach.
You should try from funcFile import func in your main file:
from funcFile import func
class Game(object):
def __init__(self):
pass
import funcFile
instance = Game()
instance.func()
I am going to attach two blocks of code, the first is the main code that is ran the second is the testClass file containing a sample class for testing purposes. To understand what's going on it's probably easiest to run the code on your own. When I call sC.cls.print2() it says that the self parameter is unfulfilled. Normally when working with classes, self (in this case) would be sC.cls and you wouldn't have to pass it as a parameter. Any advice is greatly appreciated on why this is occuring, I think it's something to do with exec's scope but even if I run this function in exec it gives the same error and I can't figure out a way around it. If you'd like any more info please just ask!
import testClass
def main():
inst = testClass.myClass()
classInfo = str(type(inst)).split()[1].split("'")[1].split('.')
print(classInfo)
class StoreClass:
def __init__(self):
pass
exec('from {} import {}'.format(classInfo[0], classInfo[1]))
sC = StoreClass()
exec('sC.cls = {}'.format(classInfo[1]))
print(sC.cls)
sC.cls.print2()
if __name__ == '__main__':
main()
class myClass:
def printSomething(self):
print('hello')
def print2(self):
print('hi')
class script(object):
def __init__(self, time_delay = 1.5):
self.time_delay = time_delay
self.lines = []
def run_script(self):
for line in self.lines:
print line
sleep(self.time_delay)
intro = script(1.5)
intro.lines = ["great", "boy"]
My guess would be that the sleep() function is from the time library. Just add
from time import *
at the beginning of the file. But, since the syntax above will import definitions as if they were declared in your file, you can use:
import time
...
time.sleep(self.time_delay)
But there is also another possibility. That sleep() has to be a function declared by you. If this is the case, you have to define it:
class script(object):
# ...
def sleep(delay):
# implementation
Note:
As #icktoofay commented, you are not using the run_script() method, so may want to add a call like:
intro.run_script()
There might be confusion on your part about "running" a class, since you don't "run" a class, but you can "run" a method of a class. Perhaps you just mean
intro.run_script()
So, first off here's my code:
import threading
print "Press Escape to Quit"
class threadOne(threading.Thread): #I don't understand this or the next line
def run(self):
setup()
def setup():
print 'hello world - this is threadOne'
class threadTwo(threading.Thread):
def run(self):
print 'ran'
threadOne().start()
threadTwo().start()
So, the problem is that within my class 'threadOne' the run function runs (as that is called by the threading module) but from there I can not called any other functions. That includes if I make more functions beneath the setup() function. For example above, in my run(self) function I try and call setup() and get 'NameError: global name 'setup' is not defined'.
Does anybody have any ideas or can they explain this to me?
Sam
setup is a method of your Thread instance. Therefore, you call it with self.setup() rather than setup(). The latter is trying to call a global function named setup which does not exist.
Since setup() is an instance method, it must accept self as its first parameter as well.
I assume you meant to do the following:
class threadOne(threading.Thread): #I don't understand this or the next line
def run(self):
self.setup()
def setup(self):
print 'hello world - this is threadOne'