How to make a Class out of list [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Hi I am new to Python and I am trying to make a class out of a list from a file and I am wondering if it is even possible or is it better to use dictionaries. My class looks like this:
class Program:
def __init__(self, name, start_time, end_time, channel):
And the list looks like it:
['Channel 1', '16.00-17.45 News', '17.45-17.50 Weather', '17.50-17.57 Friends', '17.57-18.00 Coming up', '18.00-18.15 MASH', '18.15-18.40 Thundercats]
Is there ant easy way to do it?

This is one of the approach:
data = ['Channel 1', '16.00-17.45 News', '17.45-17.50 Weather', '17.50-17.57 Friends', '17.57-18.00 Coming up', '18.00-18.15 MASH', '18.15-18.40 Thundercats']
class Program:
def __init__(self, start_time, end_time, name):
self.start_time = start_time
self.end_time = end_time
self.name = name
class Channel:
def __init__(self, channel_name, program_list):
self.channel_name = channel_name
self.program_list = program_list
plist = []
channel1 = Channel(data[0], plist)
for i in range(1, len(data)):
name = data[i][12:]
start_time = data[i][0:5]
end_time = data[i][7:12]
p = Program(start_time, end_time, name)
channel1.program_list.append(p)

Related

Python Output Gives Object Address Instead of Values [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm having a bit of trouble with this assignment, here's my current code.
This is the Class for the employees on a separate python file.
class Employee:
#Initializes the classes for the employee information
def __init__(self, name, id_number, department, title):
self.set_name = name
self.set_id_number = id_number
self.set_department = department
self.set_title = title
#Sets attributes to the information
def set_name(self, name):
self.name = name
def set_id_number(self, id_number):
self.id_number = id_number
def set_department(self, department):
self.department = department
def set_title(self, title):
self.title = title
#Returns the information's attributes
def get_name(self):
return self.name
def get_id_number(self):
return self.id_number
def get_department(self):
return self.department
def get_title(self):
return self.title
def __str__(self):
return 'Name:' + self.name + \
'\nID Number:' + self.id_number + \
'\nDepartment:' + self.department + \
'\nJob Title:' + self.title
Here is the main code that is supposed to print the information about the employees:
import employee
def main():
#Creates the three instances of the employees
emp1=employee.Employee("Susan Meyers", "47899", "Accounting", \
"Vice President")
emp2=employee.Employee("Mark Jones", "39119", "IT", "Programmer")
emp3=employee.Employee("Joy Rogers", "81774", "Manufacturing", \
"Engineer")
#Prints information about the employees
print("EMPLOYEE INFORMATION:")
print("---------------------")
print("Employee 1:")
print(emp1, '\n')
print("Employee 2:")
print(emp2, '\n')
print("Employee 3:")
print(emp3, '\n')
main()
This is the output I get when I run the 2nd file on this post:
EMPLOYEE INFORMATION:
---------------------
Employee 1:
<employee.Employee object at 0x000002BE14A959D0>
Employee 2:
<employee.Employee object at 0x000002BE14ABB0A0>
Employee 3:
<employee.Employee object at 0x000002BE14B622B0>
Not sure why this is happening, but if anyone could help, it would be much appreciated.
The string conversion function is __str__, not _str_. Adding a _ before and after should fix your problem.
More feedback, while not related to the question:
Use the following to call your main() instead. While not absolutely necessary, it is good practice. It prevents main() from being run if you use the .py file in an import statement.
if __name__ == "__main__":
main()
In the constructor of your class, the usage of the setter functions is incorrect. You need to call them instead of setting them.
Afterwards, it should work:
https://ideone.com/2mnd3g

Create new class with init [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to create new class by type function.
def create_fk_widget_from_model(model, **kwargs):
to_field = kwargs.pop('to_field', 'id')
rel = ManyToOneRel(None, model, to_field) # type: ignore
return type(
f'{model.__name__}ForeignKeyRawIdWidget',
(ForeignKeyRawIdWidget, ),
{'__init__': ForeignKeyRawIdWidget.__init__(
rel=rel,
admin_site=admin.site)}
)
But there is a problem. I need to change __init__ in new class, how to do it?
You probably want something like:
def create_fk_widget_from_model(model, **kwargs):
to_field = kwargs.pop('to_field', 'id')
rel = ManyToOneRel(None, model, to_field) # type: ignore
def __init__(self):
return ForeignKeyRawIdWidget.__init__(self, rel=rel, admin_site=admin.site)
return type(
f'{model.__name__}ForeignKeyRawIdWidget',
(ForeignKeyRawIdWidget, ),
{'__init__': __init__}
)

can two different methods have different args in a class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to add the age for users in a different method but some users might not have an age argument
class User:
"""a class to save info about every user """
def __init__(self, user_name, num_id):
self.name = name
self.mun_id = num_id
def age(self, age):
self.age = age
user1 = User("martin", "1")
print (user1.name)
Yes you can set user age separately. Example below:
user1.age(20)
print (user1.age)
#20 will print
define age = None like below and this optional argument should be the last one:
def age(self, age = None):

i want to trace this method to know why it stop looping after the second record [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i wanna to make a button to loop in all records and do a method that makes a list from ranges between tow fields and pop another record from the list and but the value in result field
i make it like in the code below and it work well just in the first record and the second record it working but without remove the record form the list and it's important for me to remove it like
then it stop working
class relate(models.Model):
_name = 'relate'
_rec_name = 'car'
#api.multi
#api.onchange('start', 'end', 'ignore')
def years_rang(self):
for rec in self.search([]):
if not rec.rang:
record = [int(x) for x in range(int(rec.start), int(rec.end) + 1)]
list = []
if rec.ignore:
try:
record.remove(int(self.ignore))
list= []
print(record)
except ValueError:
return {'warning': {'title': 'Warning!', 'message': "the Ignored year doesn't in range"}}
else:
for item in record:
range_id = self.env['yearrange'].create({'name': str(item)})
list.append(range_id.id)
rec.rang = [(4, x, None) for x in list]
else:
return
start = fields.Char(string="", required=False, )
end = fields.Char(string="", required=False, )
rang = fields.One2many(comodel_name="yearrange", inverse_name="product_id", store=True, string="Years" ,)
ignore = fields.Char(string="Ignore", required=False, )
class yearrange(models.Model):
_name = 'yearrange'
_rec_name = 'name'
name = fields.Char()
product_id = fields.Many2one(comodel_name="relate")
any kind of help will be appreciated
Adding print() in key parts helps tracing a lot.
If more is needed, import pdb; pdb.set_trace() would get you into a debugger REPL, provided that the process has a terminal (not running in a Lambda, etc).
The lack of explanation of what this code is doing and what kind of data it works on prevents an uninvolved observer from detecting any data-related bugs in it. What does self.search([]) even return?
Shadowing built-in identifiers like list is a bad idea, about as bad as having non-descriptive names like list.

How to call/run a method only one time in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to call/run a method only onetime I tried this but it didn't wotk:
class S ()
_int_(self)
self.xxx = True # i tried with and without
def Packet (event):
if (xxx == True):
self.f(event, xxx)
print xxx
else:
....
def f (event):
print "something"
Do_Somthing
xxx=False
the problem xxx is still true
Best regards
Amer
The whole class's syntax seems wrong to me. You can do something like this
class S:
def __init__(self): # Initializer function for instance members
self.flag = True
def myMethod(self): # Actual method to be called
if self.flag:
....
....
self.flag = False
Change xxx to self.xxx.
The xxx = False creates a new name binding instead of assigning to the field in your object.
Also, there are also some other syntax errors in your code. Is this the actual code you are running? The code you posted shouldn't run.
from itertools import count
class S ()
def __init__(self)
self.xxx = count()
def Packet(self, event):
if next(self.xxx) == 0:
self.f(event)
else:
....
def f(self, event):
print "something"
#Do_Something

Categories

Resources