Is it possible to return an object just by calling a class? Take for exemple, I am trying to connect to a client server and just by calling the class, I get the connection.
And if I want to start a new project on that server, I would only need to init the project and the connection is called automatically.
class LabellingProject():
def __init__(self,
web_app=False,
port=8888,
data_dir="/xxxx/xxx/",
local_files_root="/xxxx/datasets",
disable_signup_without_link=True,
username= "xxxx#xxxx"):
self.web_app = web_app
self.port = port
self.data_dir = data_dir
self.local_files_root = local_files_root
self.disable_signup_without_link = disable_signup_without_link
self.username = username
def connection(cls):
"""
"""
config = Config(web_app=cls.web_app,
port = cls.port,
data_dir = cls.data_dir,
local_files_root=cls.local_files_root,
disable_signup_without_link=cls.disable_signup_without_link,
username=cls.username)
server = LabelStudioServer()
server.start(config)
client = Client(url="http://localhost:"+str(config.port),
api_key=config.token)
return client
def create_new(self,client):
"""
"""
project = client.start_project()
return project
I want to call the function like this.
labelling = LabellingProject() => it will return the connection
project = labelling.create_new() => it will return the project and the client it should take it from the __init__.
createFromA needs to be a staticmethod as it does not operate on instances of the class Constructor
class A:
def __init__(self):
pass
def create_project(self,argA):
newA = self.Constructor.createFromA(argA)
return newA
class Constructor:
def __init__(self):
pass
#staticmethod
def createFromA(argA):
A = 2*argA
return A
cons = A()
cons.create_project(2)
Related
import alice_blue
from alice_blue import *
class socket:
#global variables
live_data=[]
socket_opened = False
#credentials
username=
password=
api_secret=
app_id=
twoFA=
#access token and alice objects
access_token = AliceBlue.login_and_get_access_token(username=username, password=password, twoFA=twoFA, api_secret=api_secret, app_id=app_id)
alice = AliceBlue(username=username, password=password, access_token=access_token, master_contracts_to_download=['NSE', 'BSE'])
#alice.start_websocket handlers
def _event_handler_quote_update(self,message):
self.live_data.append(message)
def _open_callback(self):
self.socket_opened = True
#init.py
def __init__(self):
self.alice.start_websocket(subscribe_callback=self._event_handler_quote_update,
socket_open_callback=self._open_callback,
run_in_background=True)
while (self.socket_opened==False):
pass
#subscription methods
def subscribe_nse_market(self,instruments):
for x in instruments :
self.alice.subscribe(self.alice.get_instrument_by_symbol('NSE', x), LiveFeedType.MARKET_DATA)
def subscribe_nse_snapquote(self,instruments):
for x in instruments :
self.alice.subscribe(self.alice.get_instrument_by_symbol('NSE', x), LiveFeedType.SNAPQUOTE)
a=alice_obj.socket()
b=alice_obj.socket()
ins=[ ]
a.subscribe_nse_market(ins)
b.subscribe_nse_snapquote(ins)
#but both of the below gives same content with messges mixed up
a.live_data
b.live_data
#how can i make different socket connections to store messages separately in their respective objects.
I tried making live_data & event handler methods protected/private members. But still the same.
I guess the messages are directly streamed through a single channel in the device.
#thanksAlready
Here's a simplification of your problem.
class Foo:
arr = []
def add(self, value):
self.arr.append(value)
a = Foo()
b = Foo()
a.add(1)
print(b.arr) # prints [1]
print(a.arr) # prints [1]
class Bar:
def __init__(self):
self.arr = []
def add(self, value):
self.arr.append(value)
a = Bar()
b = Bar()
a.add(1)
print(b.arr) # prints []
print(a.arr) # prints [1]
In class Foo, arr is a class attribute which means it is shared among instances.
In class Bar, arr is an instance attribute.
Looking for examples of class patterns people use to wrap PyODBC, I found this example here at SO: single database connection throughout the python application.
I don't understand how the DBConnection class works in the original example. How is DBConnector being initialized if--
cls.connection = DBConnector().create_connection()
--doesn't pass the required init values to DBConnector()? When I try to add them I get TypeError: DBConnection() takes no arguments
import pyodbc
class DBConnector(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, 'instance'):
cls.instance = super(DBConnector, cls).__new__(cls)
return cls.instance
def __init__(self, ipaddress, port, dsn, remotedsn):
self.ipaddress = ipaddress
self.port = port
self.dsn = dsn
self.remotedsn = remotedsn
self.dsnstr_default = 'OpenMode=F;OLE DB Services=-2;'
self.dbconn = None
# creates new connection
def create_connection(self):
return pyodbc.connect(self.dsnstr_default,
IPAddress = self.ipaddress,
Port = self.port,
DSN = self.dsn,
RemoteDSN = self.remotedsn,
autocommit=True)
# For explicitly opening database connection
def __enter__(self):
self.dbconn = self.create_connection()
return self.dbconn
def __exit__(self):
self.dbconn.close()
class DBConnection(object):
connection = None
#classmethod
def get_connection(cls, new=False, *args, **kwargs): << ADDED THIS
if new or not cls.connection:
cls.connection = DBConnector(*args, **kwargs).create_connection()
/\/\/\/\/\/\/\/\/\/SEE NOTE
return cls.connection
#classmethod
def GetCompanyInfo(cls):
"""execute query on singleton db connection"""
connection = cls.get_connection()
try:
connection.setencoding('utf-8')
cursor = connection.cursor()
except pyodbc.ProgrammingError:
connection = cls.get_connection(new=True)
cursor = connection.cursor()
# Start Query
cursor.execute("SELECT CompanyName, EIN, SSN FROM Company")
for cname, ein, ssn in cursor.fetchall():
result = (cname, ein, ssn)
# End Query
cursor.close()
return result
Did some homework...
I can find several examples explaining the Singleton class pattern, so I've got the Connector class to work:
a = DBConnector('127.0.0.1', '4500', 'pyauto_local', None)
a.create_connection()
# <pyodbc.Connection at 0x5772110>
a = DBConnector('127.0.0.1', '4500', 'pyauto_local', None)
a.__enter__()
# <pyodbc.Connection at 0x605f278>
a.__exit__()
I did some testing...
I had a successful test manually inserting the connection parameters into the get_connection method:
cls.connection = DBConnector('127.0.0.1', '4500', 'pyauto_local', None).create_connection()
/\/\/\/\/\/\/ NOTED ABOVE
# Testing
cx = DBConnection()
cx.GetCompanyInfo()
# ('Zep', '12-3456789', None)
Now I'm curious
I could be done if I put the connection and queries all in the one class--Monster class.
OR I understand the Car > Blue Car OOP pattern better, and in another post here at SO is an example of extending the Singleton class. This makes more sense to me.
NOW I'm really curious how the original was supposed to work:
#classmethod
def get_connection(cls, new=False):
"""Creates return new Singleton database connection"""
if new or not cls.connection:
cls.connection = DBConnector().create_connection()
return cls.connection
How to get the parameters into DBConnection class without INIT? The post is also tagged with Django, so they may have skipped an assumed Django context? Or Django gives it for free somehow?
I have a script that can run a number of different reports, based on what input it receives via the command line. All reports read from a database and return the results as a Pandas Dataframe object.
Here is the super-class, (omitting a large number of property getter and setter functions):
import mysql.connector
import pandas as p
import config
class Report(object):
_connection = None
_cursor = None
def __init__(self):
self._user = config.user
self._password = config.password
self._host = config.host
self._database = config.database
self._port = config.port
self._body_text = "Hello,\n\nPlease find attached these reports:\n\n"
self._connection = mysql.connector.connect(user=self._user, password=self._password, db=self._database,
host=self._host, port=self._port)
self._cursor = self._connection.cursor()
#property
def user(self):
return self._user
#user.setter
def user(self, value):
self._user = value
. . .
#property
def body_text(self):
return self._body_text
#body_text.setter
def body_text(self, value):
self._body_text = value
def append_body_text(self, value):
self._body_text += value
def get_data(self, server_cursor, query, columns):
server_cursor.execute(self, query)
results = server_cursor.fetchall()
data = p.DataFrame(data=results, columns=[columns])
return data
def get_today(self):
return self.today
def close(self):
self._connection_web.close()
self._connection_raw.close()
#staticmethod
def insert_variables_into_sql_statement(query, external_data):
final_query = query % external_data
return final_query
#staticmethod
def create_string_from_column(serial):
created_list = serial.tolist()
string = ', '.join(map(str, created_list))
return string
#staticmethod
def write_to_csv(data_frame, file_name):
data_frame.to_csv(config.baseDirectory + file_name, sep=',', index=False)
def generate_report(self):
data = self.get_data(self._cursor_web, self._query, self._columns)
self.write_to_csv(data, self._filename)
self.close()
Here is how my subclasses are structured:
class ExampleReport(Report):
def __init__(self):
Report.__init__(self)
self._query = """
SELECT
u.first_name AS 'First Name',
u.last_name AS 'Last Name'
FROM users AS u
"""
self._columns = "'FirstName', 'LastName'"
self._filename = "example_report.csv"
self.append_body_text("* All users")
In my main method I call the method like this:
report = Reports.ExampleReport()
report.generate_report()
When I do this, I get the following error:
AttributeError: 'ExampleReport' object has no attribute 'encode'
My database connections worked without a problem when it was terribly constructed procedural code (a working version is currently in production). It has broken now that I've tried to make it object oriented. Does anyone have any idea what I've done wrong?
EDIT: SOLVED MY OWN PROBLEM! In the get_data function in the super-class, the second line contained an erroneous self argument passed into server_cursor.execute(query) line. Once it was taken out, the error goes away.
SOLVED MY OWN PROBLEM! In the get_data function in the super-class, the second line contained an erroneous self argument passed into server_cursor.execute(query) line. Once it was taken out, the error goes away.
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()
...
So I created this class called BigIPLTM in a python script file named pycontrol.py. I also have a python server page which imports the script and creates an object. I am running into an issue when trying to call methods of this object. Error is BigIPLTM has no instance of get_pool_name. Here is my code: Also any feedback on my class would be great, since it is the first class I have written in python.
pycontrol.py:
import pycontrol.pycontrol as pycontrol
class BigIPLTM:
def __init__(self, host, user="xxxx", passwd="xxxx",
content = ['LocalLB.VirtualServer', 'LocalLB.Pool',
'LocalLB.VirtualAddress', 'LocalLB.PoolMember',
'LocalLB.Monitor', 'System.SystemInfo']):
self.host = host
self.b = pycontrol.BIGIP(hostname = host, username = user,
password = passwd, fromurl = True, wsdls = content)
def get_destination(self, vipName):
destination = self.b.LocalLB.VirtualServer.get_destination(vipName)
return destination
def get_pool_name(self, vipName):
#needs to be a list
vip = list()
vip.append(vipName)
poolName = self.b.LocalLB.VirtualServer.get_default_pool_name(vip)
return poolName
def get_vip_state(self, vipName):
'''Returns a data structure containing a vip config, status and statistics'''
vip = list()
vip.append(vipName)
state = self.b.LocalLB.VirtualServer.get_enabled_state(vip)
return state
def get_members(self, poolName):
'''Returns array of members in a pool'''
pool = list()
pool.append(poolName)
members = self.b.LocalLB.Pool.get_member(pool)
#returns 3 dimensional array(default,member_number, address/port)
return members
test.psp
def get_vip_properties(vip, env):
import pycontrol
tempDict ={}
vipList = list()
vipList.append(vip)
#get pool name
b = pycontrol.BigIPLTM(env)
tempDict['pool'] = b.get_pool_name(vipList)
#get destination address and port
tempDict['destination'] = b.get_destination(vipList)
tempDict['port'] = b.get_destination(vipList)
tempDict['vipState'] = b.get_vip_state(vipList)
#get members is a 3dimensional array (default, membernumber, address/port)
tempArray = b.get_members(b.get_pool_name(vipList))
members = list()
for row in tempArray:
for entry in row:
members.append(entry[0])
tempDict['members'] = members
tempDict['member_port'] = b.get_members(b.get_pool_name(vipList))[0][0][1]
return tempDict