passing self with other argument on function call python - python

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")

Related

Passing class objects to another class method Python

I am trying to understand where my mistake lies and I was hoping you could please help me.
I have this code:
import copy
class FooInd():
def __init__(self):
self.a=1
class Planning():
def foo(self,pop):
print(pop.a)
def main():
ind=FooInd()
Planning.foo(copy.deepcopy(ind))
if __name__ == "__main__":
Planning.main()
However I keep receiving this error:
Planning.foo(copy.deepcopy(ind))
TypeError: foo() missing 1 required positional argument: 'pop'
I believe that the mistake is not in the foo method definition, but in my class initiation of the FooInd, however I have checked the Python documentation for classes and I could not find a solution.
Does anyone have a clue of what could I try or where can I check?
Many thanks in advance!
You call Planning.foo on the class, not an instance of the class. You provided the second argument it requires, but not the self argument.
You have two choices:
Construct a Planning instance to call foo on:
def main():
ind=FooInd()
Planning().foo(copy.deepcopy(ind))
# ^^ Makes simple instance to call on
Make foo a classmethod or staticmethod that doesn't require an instance for self:
class Planning():
#staticmethod # Doesn't need self at all
def foo(pop):
print(pop.a)
I think you meant to instantiate Planning before calling methods on it:
import copy
class FooInd():
def __init__(self):
self.a = 1
class Planning():
def foo(self, pop):
print(pop.a)
def main(self):
ind = FooInd()
self.foo(copy.deepcopy(ind))
if __name__ == "__main__":
p = Planning()
p.main()
Output:
1

How to import function into a class from external file?

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()

class declaration in exec inits class, but functions don't work

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')

Most pythonic way to declare inner functions

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

Below Python Script is not giving any result

I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result.
Step 1:
Code:
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
Step 2:
ctrl + B
Step 3:
Result:
Repl Closed
That's because you're only declaring a class, not instantiating it.
Your variable avenger1 exists within the init function, therefore it isn't being called. Indentation matters in python.
Try this:
class Avengers(object):
def __init__(self):
print('hello')
if __name__ == "__main__":
avenger1 = Avengers()
You are not instantiating the class. Try something like:
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
When you instantiate a class like this, it will execute the __init__ function for that class.
First, let me fix the code
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.init(self)
okay, here you creating a class called Avengers. why its not produce anything? because you never initialize that class (creating an object).
so here we go:
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.init(self)
Avengers()
it will printing hello, but, its recursive. never end printing "hello". because each time that class is initialized, its creating an object again again and again. init is special function so, each time the class is initialized, init function will executed.
maybe what you want is like this:
class Avengers(object):
def __init__(self):
print('hello')
Avengers()
additional reference that you can read: https://www.sololearn.com/Play/Python
The previous answers are correct, but also note that Avengers class in its constructor is initializing another instance of Avengers.
This means when an Avengers object is created, it is creating another Avengers object which is creating another Avengers object and so on.
The __init__ function is falling into an infinite recursion.
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers() # this line triggers infinite recursion
avenger1.__init__(self)
avengers = Avengers() # Initiates the class

Categories

Resources