I tried to get array parameters values in another class , where and why i wrong here ?
My second python file => myModule.py :
parameters = ([])
class MyFirstClass():
def __init__(self, params):
global parameters
parameters = params
class MySecondClass():
def __init__(self):
global parameters
print parameters
class MyClassWhereIHaveAProblem(http.HTTPFactory):
proto = .....
global parameters
print parameters **// array is empty here**
class start_server():
def __init__(self, params):
self.x_params = params[0] //ip
self.y_params = int(params[1]) //port
global parameters
parameters = params[2]
def start():
reactor.listenTCP(self.y, MyClassWhereIHaveAProblem(), interface=self.x)
My first python file => Handle.py :
from myModule import MyFisrtClass
from myModule import MySecondClass
from myModule import MyClassWhereIHaveAProblem
from myModule import start_server
class Handle():
def __init__(self):
params = (["vector1", "vector2"])
self.params = (["127.0.0.1","3128", params])
def go_to_another(self):
s = start_server(self.params)
s.start()
if __name__ == '__main__':
H = Handle()
H.go_to_another()
I tried to get array parameters values in another class , where and why i wrong here ?
It looks like you are simply:
forgetting the second set of double underscores for the special method names
making typos in the class names, you had "First" spelled "Fisrt"
you never did anything to use the MySecondClass class, so I initialized one in your main routine with: y = MySecondClass()
Handle.py:
#!/usr/bin/env python
from myModule import MyFirstClass
from myModule import MySecondClass
class Handle():
def __init__(self):
self.params = (["ele1","ele2","ele3"])
def go_to_another(self):
X = MyFirstClass(self.params)
if __name__ == '__main__':
H = Handle()
H.go_to_another()
y = MySecondClass()
myModule.py:
#!/usr/bin/env python
parameters = ([])
class MyFirstClass():
def __init__(self, params):
global parameters
parameters = params
class MySecondClass():
def __init__(self):
global parameters
print 'this should not be empty: %s' % parameters # array is no longer empty here
Output:
this should not be empty: ['ele1', 'ele2', 'ele3']
You have X = MyFisrtClass(self.params) instead of X = MyFirstClass(self.params)! Also __init should be __init__.
You are printing the variable when the class is first defined, but defining the variable when the class is initialized.
In Python, anything here:
class MyClass:
# here
Is evaluated as soon as the interpreter reaches that line-- not when the class is initialized.
Try running this code to get a better idea of what I mean:
my_global_var = 'set initially!'
class MyClass():
# Will print 'set initially', as this
# print statement is run before an instance of the
# class ever gets initialized,
print 'in class defn: %s' % my_global_var
def __init__( self ):
global my_global_var
my_global_var = 'set by the class instance!'
x = MyClass()
# Will print 'set by the class instance', as now
# you are printing it after the class has been initialized
# at least once
print 'after class is initialized: %s' % my_global_var
For your code:
# I have a problem here
class MyClassWhereIHaveAProblem(http.HTTPFactory):
#proto = .....
#global = parameters
print 'not set here, this is static: %s' % parameters #**// array is empty here**
def __init__(self):
print 'now it is set: %s' % parameters
But make sure you actually initialize one of those MyClassWhereIHaveAProblem.
From what I think is the documentation:
listenTCP(port, factory, backlog=50, interface='')
port a port number on which to listen
factory a twisted.internet.protocol.ServerFactory instance
backlog size of the listen queue
interface The local IPv4 or IPv6 address to which to bind; defaults to '', ie all IPv4 addresses. To bind to all IPv4 and IPv6 addresses, you must call this method twice.
So I think you want to simply do:
listenTCP(self.y_params, YourProblemClass(), interface=self.x_params)
Where:
- y_params is what you called the port, and
- x_params is what you called the address.
ok, I'll go to sleep :) I had also itinialise my object (logical), now everything is ok, Thanks for your time Alex.B, solution here:
class MyClassWhereIHaveAProblem(http.HTTPFactory):
proto = .....
def __init__(self):
http.HTTPFactory.__init__(self)
global parameters
print parameters
Related
I have a class in Python that initializes the attributes of an environment. I am attempting to grab the topographyRegistry attribute list of my Environment class in a separate function, which when called, should take in the parameters of 'self' and the topography to be added. When this function is called, it should simply take an argument such as addTopographyToEnvironment(self, "Mountains") and append it to the topographyRegistry of the Environment class.
When implementing what I mentioned above, I ran into an error regarding the 'self' method not being defined. Hence, whenever I call the above line, it gives me:
print (Environment.addTopographyToEnvironment(self, "Mountains"))
^^^^
NameError: name 'self' is not defined
This leads me to believe that I am unaware of and missing a step in my implementation, but I am unsure of what that is exactly.
Here is the relevant code:
class EnvironmentInfo:
def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):
self.perceivableFood = perceivableFood
self.perceivableCreatures = perceivableCreatures
self.regionTopography = regionTopography
self.lightVisibility = lightVisibility
class Environment:
def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility):
logging.info("Creating new environment")
self.creatureRegistry = []
self.foodRegistry = []
self.topographyRegistery = []
self.lightVisibility = True
def displayEnvironment():
creatureRegistry = []
foodRegistry = []
topographyRegistery = ['Grasslands']
lightVisibility = True
print (f"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery} Contains Light: {lightVisibility}")
def addTopographyToEnvironment(self, topographyRegistery):
logging.info(
f"Registering {topographyRegistery} as a region in the Environment")
self.topographyRegistery.append(topographyRegistery)
def getRegisteredEnvironment(self):
return self.topographyRegistry
if __name__ == "__main__":
print (Environment.displayEnvironment()) #Display hardcoded attributes
print (Environment.addTopographyToEnvironment(self, "Mountains"))#NameError
print (Environment.getRegisteredEnvironment(self)) #NameError
What am I doing wrong or not understanding when using 'self'?
Edit: In regard to omitting 'self' from the print statement, it still gives me an error indicating a TypeError:
print (Environment.addTopographyToEnvironment("Mountains"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Environment.addTopographyToEnvironment() missing 1 required positional argument: 'topographyRegistery'
Comments
Despite having def getRegisteredEnvironment(self): it wasn't indented, so it's not recognized as a class method.
self is a keyword used in conjunction with classes (class methods or attributes) - not functions. self is implied to be the instantiated object (eg a = Environment(...) -> self would refer to a) or the module's (I can't think of the proper term) class.
You didn't have your addTopographyToEnvironment class method defined.
In terms of your Environment class, you aren't using the variables you are passing to the class, so I made that change as well - I don't know if that was intentional or not.
As per your comment from the other answer, if you had def my_class_method(self) and you try to invoke it through an object with additional parameters, like so a = my_object(); a.my_class_method("Mountains"), you should get an error of the sorts, "2 positional arguments passed, expected 1.".
Your main problem is that you are doing Environment.class_method() and not creating an object from the class. Do a = Environment(whatever arguments here) to create an object from the class, then do a.addTopographyToEnvironment("Mountains") to do what you were going to do with "Mountains" and that object. What you have currently may be right, its just is missing the proper implementation, but the below article does a great job explaining the differences between all of them (Class Methods vs Static Methods vs Instance Methods), and is definitely worth the read.
class EnvironmentInfo:
def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):
self.perceivableFood = perceivableFood
self.perceivableCreatures = perceivableCreatures
self.regionTopography = regionTopography
self.lightVisibility = lightVisibility
class Environment:
def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility):
logging.info("Creating new environment")
self.creatureRegistry = creatureRegistry
self.foodRegistry = foodRegistry
self.topographyRegistery = topographyRegistery
self.lightVisibility = lightVisibility
def displayEnvironment(self):
creatureRegistry = []
foodRegistry = []
topographyRegistery = ['Grasslands']
lightVisibility = True
print (f"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery} Contains Light: {lightVisibility}")
def addTopographyToEnvironment(self, environment):
return "Whatever this is supposed to return." + environment
def getRegisteredEnvironment(self):
return self.topographyRegistry
if __name__ == "__main__":
print (Environment.displayEnvironment()) #Display hardcoded attributes
print (Environment.addTopographyToEnvironment("Mountains"))#NameError
print (Environment.getRegisteredEnvironment()) #NameError
Object Instantiation In Python
With all that out of the way, I will answer the question as is posed, "Is there a way to grab list attributes that have been initialized using self and append data to them in Python?". I am assuming you mean the contents of the list and not the attributes of it, the attributes would be "got" or at least printed with dir()
As a simple example:
class MyClass:
def __init__(self, my_list):
self.my_list = my_list
if __name__ == "__main__":
a = MyClass([1, 2, 3, 4, 5])
print(a.my_list)
# will print [1, 2, 3, 4, 5]
a.my_list.append(6)
print(a.my_list)
# will print [1, 2, 3, 4, 5, 6]
print(dir(a.my_list))
# will print all object methods and object attributes for the list associated with object "a".
Sub Classing In Python
Given what you have above, it looks like you should be using method sub classing - this is done with the keyword super. From what I can guess, it would look like you'd implement that kind of like this:
class EnvironmentInfo:
def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):
self.perceivableFood = perceivableFood
self.perceivableCreatures = perceivableCreatures
self.regionTopography = regionTopography
self.lightVisibility = lightVisibility
class Environment(EnvironmentInfo):
def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility, someOtherThingAvailableToEnvironmentButNotEnvironmentInfo):
logging.info("Creating new environment")
super.__init__(foodRegistry, creatureRegistry, topographyRegistery, lightVisibility)
self.my_var1 = someOtherThingAvailableToEnvironmentButNotEnvironmentInfo
def displayEnvironment(self):
creatureRegistry = []
foodRegistry = []
topographyRegistery = ['Grasslands']
lightVisibility = True
print (f"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery} Contains Light: {lightVisibility}")
def addTopographyToEnvironment(self, environment):
return "Whatever this is supposed to return." + environment
def getRegisteredEnvironment(self):
return self.topographyRegistry
def methodAvailableToSubClassButNotSuper(self)
return self.my_var1
if __name__ == "__main__":
a = Environment([], [], [], True, "Only accessible to the sub class")
print(a.methodAvailableToSubClassButNotSuper())
as the article describes when talking about super(), methods and attributes from the super class are available to the sub class.
Extra Resources
Class Methods vs Static Methods vs Instance Methods - "Difference #2: Method Defination" gives an example that would be helpful I think.
What is sub classing in Python? - Just glanced at it; probably an okay read.
Self represents the instance of the class and you don't have access to it outside of the class, by the way when you are calling object methods of a class you don't need to pass self cause it automatically be passed to the method you just need to pass the parameters after self so if you want to call an object method like addTopographyToEnvironment(self, newVal) you should do it like:
Environment.addTopographyToEnvironment("Mountains")
and it should work fine
I have 3 files: main, calc, and settings organized like this:
# main.py
import settings as s
import calc as c
class Main:
def __init__(self):
calc = c.Calc()
self.my_var = user_input
s.changing_variable = self.my_var
def run(self):
calc.do_something()
# calc.py
import settings as s
class Calc:
def __init__(self):
self.test_variable = s.changing_variable
# settings.py
changing_variable = original_value
All code is run from the main file. I have an original value in the settings file that I now want to change based on the user input in my main file. This value should then be changed globally for all files.
The problem is that it is changed for the main file but not for the calc file. I assume this is because I import settings at the beginning of calc.py and therefore override the user input again.
Does anyone have any idea how to solve this without having to pass the user input variable around in the function calls?
First you need to initialize the variable once during the application life and make it in the global scope, so "settings.py" becomes:
# settings.py
def defing_global_variables():
global changing_variable
changing_variable = original_value
and invoke the fuction "defing_global_variables" in the main module to initialize the global variables.
in "main.initi" function, set the value of "changing_variable" to user_input before instantiating the calc object, and make calc object in the class scope by using self.calc instead of calc, so you can invoke this object again in "main.run" function.
Here is the all modifications for your code:
# main.py
import settings as s
import calc as c
# initialize golobal variables # Added lines
s.defing_global_variables() # Added lines
class Main:
def __init__(self):
self.my_var = 500 # user_input
s.changing_variable = self.my_var
self.calc = c.Calc() # instinteat the object after stting the value, and make it in class scope by adding "self."
def run(self):
self.calc.do_something() # adding self.
a = Main()
a.run()
c2 = c.Calc()
s.changing_variable = 123 # new value
c2.print_global_var()
# the results
# 500
# 123
# calc.py
import settings as s
class Calc:
def __init__(self):
self.test_variable = s.changing_variable
def do_something(self):
print(self.test_variable)
def print_global_var(self):
print(s.changing_variable)
# settings.py
def defing_global_variables():
global changing_variable
changing_variable = 0 # original_value
Good Luck :)
I have been playing around with scripts for a couple of weeks and have not had any issues, but I am now trying to create a class and am running into problems.
I don't fully understand it myself but I am getting this error NameError: global name 'instance_status_check' is not defined when I try to create an instance of the following class.
I am fully aware the class isn't doing much at this time but I can't move on until I resolve the problem. Can someone explain what I am doing wrong?
import sys
import boto
import boto.ec2
class Monitor:
def __init__(self,conn,identifier):
self.connection = conn
self.identifier = identifier
self.dispatcher ={'1': instance_status_check}
def user_menu():
for i, value in self.dispatcher.itertems():
print "Please press {i} for {value}".format(i,value)
def instance_status_check():
pass
You are missing the self parameter from both methods and it is iteritems not itertems:
class Monitor: # upper case for class names
def __init__(self,conn,identifier):
self.connection = conn
self.identifier = identifier
self.dispatcher ={'1': self.instance_status_check} # call self.instance_status_check()
def user_menu(self): # self here
for i, value in self.dispatcher.iteritems():
print("Please press {i} for {value}".format(i,value))
def instance_status_check(self): # self here
return "In status method"
m = Monitor(3,4)
print(m.dispatcher["1"]())
In status method
I suggest you have a look at the classes tutorial from the docs
You have this error because you have defined instance_status_check after you are already using it.
Move the declaration above the class:
def instance_status_check():
pass
class monitor:
def __init__(self,conn,identifier):
self.connection = conn
self.identifier = identifier
self.dispatcher ={'1': instance_status_check}
def user_menu(self):
for i, value in self.dispatcher.itertems():
print "Please press {i} for {value}".format(i,value)
Also, this will not print Please press 1 for instance_status_check it will print something like Please press 1 for <function instance_status_check at 0xsomething>
I have S8Test.py with testFirewallS8 class and some methods. I want to access the method declared inside this class form the main method. and set the variable from that method another python file contains the same variable to modify. How can I do this:
#! /usr/bin/env python
__author__ = 'Milson Munakami'
__revision__ = '0.0.2'
import json
import urllib
import httplib
from scapy.all import *
import unittest
import os, sys, socket, struct, select, time
from threading import Thread
import logging
import traceback
from mininet.net import Mininet
from mininet.node import OVSSwitch, OVSKernelSwitch, Controller, RemoteController
from mininet.log import setLogLevel, info
from mininet.cli import CLI
class TestFirewallS8( unittest.TestCase ):
def setUp(self):
self.controllerIp="127.0.0.1"
self.switch = "00:00:00:00:00:00:00:01"
self.destinationIp = "10.0.0.1"
self.startTime_ = time.time()
self.failed = False
self.reportStatus_ = True
self.name_ = "Firewall"
self.log = logging.getLogger("unittest")
"Create an empty network and add nodes to it."
self.net = Mininet( controller=RemoteController )
#Want to move this method call from outside the setUp method because it need to be initiated only once for the whole test but
#it need to access the class variables and pass it to another python file i.e. Events.py to perform some task on the object i.e. self
#self.CreateNet()
def createNet(self):
print "Me"
info( '*** Adding controller\n' )
self.net.addController( 'c0' , controller=RemoteController,ip= "127.0.0.1", port=6633)
info( '*** Adding hosts\n' )
h1 = self.net.addHost( 'h1', ip='10.0.0.1' )
h2 = self.net.addHost( 'h2', ip='10.0.0.2' )
h3 = self.net.addHost( 'h3', ip='10.0.0.3' )
info( '*** Adding switch\n' )
s1 = self.net.addSwitch( 's1' )
info( '*** Creating links\n' )
self.net.addLink( h1, s1 )
self.net.addLink( h2, s1 )
self.net.addLink( h3, s1 )
def setFinalcondition(self):
Precondition.SetFinalcondition(self)
info( '*** Stopping network' )
self.net.stop()
def testCreateFlow(self):
Events.createFlow(self)
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestFirewallS8))
return suite
if __name__ == '__main__':
#How to get run the method of testFirewallS8 class and set the variable of it like self.net
suiteFew = unittest.TestSuite(testCreateFlow)
TestFirewallS8("createNet")
In another Events.py I have:
def createFlow(self):
info( '*** Starting network\n')
self.net.start()
info( '*** Testing network connecivity\n')
#self.net.pingAll()
h1 = self.net.get('h1')
h3 = self.net.get('h3')
h1.cmd('ping -c1 %s' % h3.IP())
I'm not completely clear what you're asking, but if you have a class definition:
class MyClass(object):
def __init__(self, name):
self.name = name
def big_name(self):
print(self.name.upper())
After you instantiate it (MyClass('Bob')), assign it to a variable.
bob = MyClass('Bob')
You can then execute methods of that class instance by simply accessing it's attributes.
bob.big_name # accesses the "big_name" attribute on "bob": a bound method
bob.big_name() # executes the bound method
Attributes can also be variables, and you can freely access and reassign them as well:
bob.name # accesses the "name" attribute on "bob": a string
bob.name = 'Robert' # reassigns the "name" attribute
I have the following class
class GUI( QtGui.QMainWindow ):
'''
classdocs
'''
"""**********************************************************************"""
""" Constructor """
"""**********************************************************************"""
def __init__( self, parent = None ):
self.udpClass = MCUDP.MCUDP()
def insertText( self, string ):
string = time.ctime() + ': ' + string + '\n'
self.messageField.insertPlainText( string )
And I also have MCUDP class created in the GUI class. My question is how can I reach the GUI class insertText function in MCUDP
UPDATED
this is the MCUDP
'''
Created on 09.06.2011
#author: robu
'''
import socket
import time
import MCGui;
class MCUDP( object ):
'''
classdocs
'''
"""**********************************************************************"""
""" UDP: Broadcasting """
"""**********************************************************************"""
def UDPBroadcast( self, ip = "255.255.255.255", UDPport = 15000, message = 'whoisthere', timeout = 10, TCPport = 30000 ):
# ip="255.255.255.255" stands for a broadcast
ip = str( ip )
s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP )
s.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, True )
s.settimeout( timeout )
ownIP = socket.gethostbyname( socket.gethostname() )
if message.upper() == 'WHOISTHERE':
message = message + ';' + ownIP + ':' + str( TCPport )
#print "Trying to send '%s' to IP %s, Port %s!" %(message, ip, port)
#self.Eingang.put("Trying to send '%s' to IP %s, Port %s!" %(message, ip, UDPport))
s.sendto( message, ( ip, UDPport ) )
answer = "%s: '%s' broadcasted to %s!" % ( time.asctime(), message, ip )
GUI.insertText( 'test' );
#print answer
s.close()
return answer
You have two objects that need to communicate with each other, which is a fairly standard communication problem. There's a number of ways that this problem can be solved:
(1) Dependency Injection - Make your MCUDP() class require the MCGUI class at construction time.
You'll then have it available whenever you need:
class MCUDP(object):
def __init__(self, gui): self.gui = gui
def UDPBroadcast(...):
# ... as necessary ...
self.gui.insertText("YourText")
class MCGUI(...)
def __init__( self, parent = None ):
self.udpClass = MCUDP.MCUDP(self)
If you do this your MCUDP class becomes dependent on an object that implements all the methods of self.gui that MCUDP uses. In other words, MCUDP is now coupled directly to the MCGUI class. Of course, the MCGUI class is already dependent on MCUDP to some extent.
(2) Message passing - In Qt, Signals and slots. The idiomatic Qt route uses messages instead of function calls:
class MCGUI(...)
def __init__( self, parent = None ):
self.udpClass = MCUDP.MCUDP()
self.connect(self.udpClass, PYSIGNAL("textUpdated"), self.insertText);
And then you just need to make your MCUDP class a QObject so that it can emit events:
class MCUDP(QObject):
def __init__(self, parent = None):
QObject.__init__(self, parent)
def UDPBroadcast(...):
# ... as necessary ...
self.emit(PYSIGNAL("textUpdated"), ("yourText",))
The benefit of this is now MCUDP doesn't need to know anything about the MCGUI class which will make both testing and future changes easier.
It is available as insertText during declaration and as GUI.insertText or GUI().insertText during execution. If you are not sure where you are, try both :).
I would say which one you need if you posted the actual full code.
[update]
Your MCDUP class is not 'created in the GUI class'. You just create a an instance of MCDUP and hold a reference to it inside GUI. The reference is one-way, so if you need to access parent GUI instance, you need a back-reference, something like:
class GUI(QtGui.QMainWindow):
def __init__(self, parent=None):
self.udp = MCUDP.MCUDP(gui=self)
And then in MCDUP:
class MCUDP(object):
def __init__(self, gui):
self.gui = gui
def udp_broadcast(self, ...):
...
self.gui.insertText('test')
...
I also made the code a little more PEP8-friedly.
Generally the second option suggested by Kaleb Pederson is the way to go.
Nevertheless if you want a reference to the MainWindow you can save it
as a property of your QApplication's instance.
When you start your application:
app = QApplication(sys.argv)
...
mainwindow = GUI()
app.setProperty("mainwindow", QVariant(mainwindow))
Then when you want to use the reference:
...
mainwindow = qApp.property('mainwindow').toPyObject()
...