I am trying to create a python program that adds and removes names to a certain category. While I'm pretty sure the use a heap would be a good method for this program, I may be thinking of the wrong data structure. I'm still very new to programming and I am very unsure as what to do.
class table():
__slots__ = ('time','volunteers')
def mkTable(time,name):
tbl = table()
tbl.time = time
tbl.volumteers = name
return tbl
Does anyone have any advice?
Related
I am trying to write a data processing script and I think I'm misinterpreting the structure of Object Oriented Programming in Python.
I have sets of simulations that keep some variables constant and others which change according to the sim. I'm trying to contain the set of sims in a parent object and include a list of sims as an attribute, which are defined as a child object:
class Sim_set(path) :
def __init__ :
f = open(path)
self.fixed_attributes = fixed_attributes(f)
sims = [Sim(data) for data in f]
class Sim(Sim_set) :
def __init__(data) :
Sim_set.__init__()
self.variable_attributes = variable_attributes(data)
def derived_attributes() :
self.derived_attributes = math(self.variable_attributes,self.fixed_attributes)
The problem is that it looks like for each Sim, a new instance of Sim_set is created, when in reality I want the opposite: I want a single instance of Sim_set, with attributes that Sim can fetch, and many instances of Sim, contained in Sim_set.
I apologize if this is a rather broad question, but am I doing this right?
EDIT: So based on the answers so far, what I'm doing now is:
So what I am doing now is :
class Sim :
def __init__(data,sim_set) :
self.sim_set = sim_set
self.var_attr = f(data)
def deriv_attr() :
self.deriv_attr = g(self.var_attr,self.sim_set.fixed_attr)
It seems to work, but the crux of the question is really, "is this a good habit to have"?
So, Sim_set represents a set of simulations, and Sim represents of single simulation. It seems weird to me that a simulation inherits from a set of simulations.
I would break the parent-child relationship between Sim and Sim_set. Sim_set can still contain a collection of Sims but I don't think the parent-child relationship is appropriate here. Instead, I might add a new object, let's call it "Simluation_Lab" which is responsible for creating Sims and Sim_sets, and then populating them with the correct values.
You might also want to read up on Dependency Injection, it might help in this situation: https://medium.com/#shivama205/dependency-injection-python-cb2b5f336dce
If Sim_set is parent of Sim, every Sim is also a Sim_set
Every time you create a new Sim object it will create a new Sim_set
def __init__(data)
Sim_set.__init__()
self.variable_attributes = variable_attributes(data)
Look this code you are calling the __ init __ () method of Sim_set class this method is for object initialization (Constructor) So you are saying Sim is also Sim_set
It sounds like a Sim belongs to a Sim_set rather than IS a sim_set
This can be achieved by creating an attribute that it´s class is Sim_set
I leave you the Repl.it
https://repl.it/#AndrsFernndez/DesertedDarkcyanFlashmemory#main.py
Right now I am learning Python and struggling with a few concepts of OOP, one of that being how difficult it is (to me) to dynamically initialize class instances and assign them to a dynamically generated variable name and why I am reading that I shouldn't do that in the first place.
In most threads with a similar direction, the answer seems to be that it is un-Pythonic to do that.
For example generating variable names on fly in python
Could someone please elaborate?
Take the typical OOP learning case:
LOE = ["graham", "eric", "terry_G", "terry_J", "john", "carol"]
class Employee():
def __init__(self, name, job="comedian"):
self.name = name
self.job = job
Why is it better to do this:
employees = []
for name in LOE:
emp = Employee(name)
employees.append(emp)
and then
for emp in employees:
if emp.name == "eric":
print(emp.job)
instead of this
for name in LOE:
globals()[name] = Employee(name)
and
print(eric.job)
Thanks!
If you dynamically generate variable names, you don't know what names exist, and you can't use them in code.
globals()[some_unknown_name] = Foo()
Well, now what? You can't safely do this:
eric.bar()
Because you don't know whether eric exists. You'll end up having to test for eric's existence using dictionaries/lists anyway:
if 'eric' in globals(): ...
So just store your objects in a dictionary or list to begin with:
people = {}
people['eric'] = Foo()
This way you can also safely iterate one data structure to access all your grouped objects without needing to sort them from other global variables.
globals() gives you a dict which you can put names into. But you can equally make your own dict and put the names there.
So it comes down to the idea of "namespaces," that is the concept of isolating similar things into separate data structures.
You should do this:
employees = {}
employees['alice'] = ...
employees['bob'] = ...
employees['chuck'] = ...
Now if you have another part of your program where you describe parts of a drill, you can do this:
drill['chuck'] = ...
And you won't have a name collision with Chuck the person. If everything were global, you would have a problem. Chuck could even lose his job.
I got for example the following structure of a class.
class Company(object):
Companycount = 0
_registry = {}
def __init__(self, name):
Company.Companycount +=1
self._registry[Company.Companycount] = [self]
self.name = name
k = Company("a firm")
b = Company("another firm")
Whenever I need the objects I can access them by using
Company._registry
which gives out a dictionary of all instances.
Do I need reasonable names for my objects since the name of the company is a class attribute, and I can iterate over Company._registry?
When loading the data from the database does it matter what the name of the instance (here k and b) is? Or can I just use arbitrary strings?
Both your Company._registry and the names k and b are just references to your actual instances. Neither play any role in what you'd store in the database.
Python's object model has all objects living on a big heap, and your code interacts with the objects via such references. You can make as many references as you like, and objects automatically are deleted when there are no references left. See the excellent Facts and myths about Python names and values article by Ned Batchelder.
You need to decide, for yourself, if the Company._registry structure needs to have names or not. Iteration over a list is slow if you already have a name for a company you wanted to access, but a dictionary gives you instant access.
If you are going to use an ORM, then you don't really need that structure anyway. Leave it to the ORM to help you find your objects, or give you a sequence of all objects to iterate over. I recommend using SQLAlchemy for this.
the name doesn't matter but if you are gonna initialize a lot of objects you are still gonna make it reasonable somehow
Fairly new to Python and very new to SQLAlchemy. Wondering how I can use a for loop to make multiple SQLAlchemy records from a list. Here's a very simplified version of what I have.
class ListItem(Base):
__tablename__ = list_items
id = Column(Integer, primary_key=True)
item = Column(String(50))
def list_to_ListItem(list_of_things):
for thing in list_of_things:
listitem = ListItem()
listitem.item = thing
I haven't yet run this because there's actually a lot more to my code that still needs to be worked out, but I'm under the impression that, instead of creating a record in list_items for each thing in list_of_things, this will simply create one record assigned to listitem that it will overwrite with every iteration of the for loop.
So how do I do this? Like I said, I'm fairly new to Python, but I've heard something about factory functions that I don't understand but which, at least in name, sounds promising for this problem. Thanks in advance!
List comprehension?
list_items = [ListItem(item=thing) for thing in list_of_things]
Suppose I am building a composite set of types:
def subordinate_type(params):
#Dink with stuff
a = type(myname, (), dict_of_fields)
return a()
def toplevel(params)
lots_of_types = dict(keys, values)
myawesomedynamictype = type(toplevelname, (), lots_of_types)
#Now I want to edit some of the values in myawesomedynamictype's
#lots_of_types.
return myawesomedynamictype()
In this particular case, I want a reference to the "typeclass" myawesomedynamictype inserted into lots_of_types.
I've tried to iterate through lots_of_types and set it, supposing that the references were pointed at the same thing, but I found that the myawesomedynamictype got corrupted and lost its fields.
The problem I'm trying to solve is that I get values related to the type subordinate_type, and I need to generate a toplevel instantiation based on subordinate_type.
This is an ancient question, and because it's not clear what the code is trying to do (being a code gist rather than working code), it's a little hard to answer.
But it sounds like you want a reference to the dynamically created class "myawesomedynamictype" on the class itself. A copy of (I believe a copy of) the dictionary lots_of_types became the __dict__ of this new class when you called type() to construct it.
So, just set a new attribute on the class to have a value of the class you just constructed; Is that what you were after?
def toplevel(params)
lots_of_types = dict(keys, values)
myawesomedynamictype = type(toplevelname, (), lots_of_types)
myawesomedynamictype.myawesomedynamictype = myawesomedynamictype
return myawesomedynamictype()