I have a couple of Classes defined.
Both of these classes take a json file as input, and extract the data into a class instance, and places them into a dictionary.
So all of my EmployeeProfile instances are stored in a dictionary called SP, with the employees email as the key, and the class instance as the value.
All of my RiskProfile instances are stored in a dictionary called RISKS, with the risk_ID as the key and the class instance as the value.
class EmployeeProfile:
def __init__(self, profile):
self.displayname = profile.get('displayName')
self.email = profile.get('email')
self.firstname = profile.get('firstName')
self.surname = profile.get('surname')
self.fullname = profile.get('fullName')
self.costcode = profile.get('work').get('custom')\
.get('Cost Category_t9HHc')
self.title = profile.get('work').get('title')
self.department = profile.get('work').get('department')
self.city = profile.get('work').get('site')
self.id = profile.get('work').get('employeeIdInCompany')
self.manageremail = ''
self.costline = 'N/A'
self.groups = {}
self.attest = {}
class RiskProfile:
def __init__(self, risk_profile):
self.ID = risk_profile.get('ID')
self.key = risk_profile.get('Key')
self.name = risk_profile.get('Name')
self.description = risk_profile.get('Description', '')
self.owner = risk_profile.get("Owner_DisplayName")
self.assignedto = risk_profile.get("AssignedTo_DisplayName")
self.email = None
self.costline = ''
self.notes = ''
self.assessmentlevel = int(risk_profile.get("AssessmentLevel"))
self.rating = ''
self.workflow = risk_profile.get('WorkflowState')
Now when I do something like:
for profile in SP:
print(SP[profile].{here i see the attribute of the class instance})
So I can see a selection of the attributes I may want to print or change etc...
print(SP[profile].department)
or
print(SP[profile].name)
However when I do the same for RiskProfile instances I do not get the list of attributes.
If I enter them manually my code still works, but does anyone know why this is not working the same way?
for profile in RISKS:
print(RISK[profile].{I never get a list of attributes})
I use Anaconda with Spyder.
I found this fantasy name generator here.
I am trying to adapt the code to suit my purpose. I want to create an NPC name automatically, using the function name_gen within the class NPC. With the NPC characteristics being:
class NPC:
def __init__(self, name, age, gender):
self.name = name_gen
self.age = 25
self.gender = M
The code from the name generator I need is the following:
from random import randrange
def line_appender(file_path, target):
file = open(file_path, "r")
splitfile = file.read().splitlines()
for line in splitfile:
target.append(line)
def name_selector(target_list):
selected = target_list[randrange(len(target_list))]
return selected
def name_builder(first_name_list_path, last_name_list_path):
first_name_list = []
last_name_list = []
line_appender(first_name_list_path, first_name_list)
line_appender(last_name_list_path, last_name_list)
first_name_selected = name_selector(first_name_list)
last_name_selected = name_selector(last_name_list)
name = first_name_selected+" "+last_name_selected
return name
Now the only thing I think I still need to do, is to generate the name from within the class NPC. I thought doing something like:
def name_gen
if gender == "M":
name = name_builder("first_name_male.txt", "last_name.txt")
elif gender == "F":
name = name_builder("first_name_female.txt", "last_name.txt")
But I don't understand how to make the name_gen function check the class NPC properties,
so that it generates the desired name.
Could someone perhaps help me out?
EDIT
Thank you for all the solutions! I am pretty new to Python; In order to test Samwises solution, I tried to run it as a separate script (in order to check whether I would get a name) with the code below. It does however not print anything. I'm putting this in an EDIT because I think it might be a trivial question. If it is worth posting a separate question, please let me know:
import random
running = True
npc_input_messsage = "npc = NPC(25, 'M')"
class NameChooser:
def __init__(self, file_path):
with open(file_path) as f:
self._names = f.read().splitlines()
def choice(self):
return random.choice(self._names)
first_choosers = {
"M": NameChooser("first_name_male.txt"),
"F": NameChooser("first_name_female.txt"),
}
last_chooser = NameChooser("last_name.txt")
def name_gen(gender):
return f"{first_choosers[gender].choice()} {last_chooser.choice()}"
class NPC:
def __init__(self, age, gender):
self.name = name_gen(gender)
self.age = age
self.gender = gender
while running:
npc = input(npc_input_messsage)
# I'm entering npc = NPC(25, "M")
print(npc)
Your name generator is a little over-complicated IMO. I'd suggest wrapping all the file reading and name selection stuff in a simple class so you can define it once and then instantiate it for each of your name lists. Putting the file reading part in __init__ means you only do it once per list instead of re-reading the file each time you need to pick a name.
import random
class NameChooser:
def __init__(self, file_path):
with open(file_path) as f:
self._names = f.read().splitlines()
def choice(self):
return random.choice(self._names)
Now you can define three NameChoosers and a name_gen function that picks among them:
first_choosers = {
"M": NameChooser("first_name_male.txt"),
"F": NameChooser("first_name_female.txt"),
}
last_chooser = NameChooser("last_name.txt")
def name_gen(gender):
return f"{first_choosers[gender].choice()} {last_chooser.choice()}"
And now you can define an NPC class that takes age and gender as arguments to the constructor, and picks a random name using name_gen():
class NPC:
def __init__(self, age, gender):
self.name = name_gen(gender)
self.age = age
self.gender = gender
def __str__(self):
return f"{self.name} ({self.age}/{self.gender})"
npc = NPC(25, "M")
print(npc) # prints "Bob Small (25/M)"
I think you're confused about OOP concepts.
First, let's edit your class:
class NPC:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
See, I have assigned parameter values to the attributes.
Now let's make changes to your function:
def name_gen(gender):
if gender == "M":
name = name_builder("first_name_male.txt", "last_name.txt")
elif gender == "F":
name = name_builder("first_name_female.txt", "last_name.txt")
return name
Here I have added a parameter to your function since you're using its value.
Now let's create an instance for your class.
npc = NPC("Vishwas", 25, "M") # Instance of the class
print(name_gen(npc.gender)) # Print generated name
A straightforward way to make happen automatically would be to simply call the name generator from with the NPC.__init__() method. In the code below it's been made a private method of the class by starting its name with an underscore character. Note that the call to it has to wait until all the instance attributes it references have been assigned value.
from random import randrange
class NPC:
def __init__(self, age, gender):
self.age = age
self.gender = gender
self.name = self._name_gen()
def _name_gen(self):
if self.gender == "M":
name = name_builder("first_name_male.txt", "last_name.txt")
elif self.gender == "F":
name = name_builder("first_name_female.txt", "last_name.txt")
return name
def line_appender(file_path, target):
file = open(file_path, "r")
splitfile = file.read().splitlines()
for line in splitfile:
target.append(line)
def name_selector(target_list):
selected = target_list[randrange(len(target_list))]
return selected
def name_builder(first_name_list_path, last_name_list_path):
first_name_list = []
last_name_list = []
line_appender(first_name_list_path, first_name_list)
line_appender(last_name_list_path, last_name_list)
first_name_selected = name_selector(first_name_list)
last_name_selected = name_selector(last_name_list)
name = first_name_selected+" "+last_name_selected
return name
if __name__ == '__main__':
npc1 = NPC(25, 'M')
print(f'{npc1.name!r}')
npc2 = NPC(21, 'F')
print(f'{npc2.name!r}')
I am trying to get one account from some branch but somewhere i am missing something. This line is from method -> but the result is <main.SavingAccount object at 0x000001F2563CEFD0>
class Branch:
def __init__(self, branch_code, city):
self.branch_code = branch_code
self.city = city
self.account_list = []
self.loan_list = []
def getAccount(self, acc_no):
for account in self.account_list:
if account.acc_no == acc_no:
return account
print(f2.getAccount(300005))
try this:
class Branch:
def __init__(self, branch_code, city):
self.branch_code = branch_code
self.city = city
self.account_list = []
self.loan_list = []
def getAccount(self, acc_no):
for account in self.account_list:
if account == acc_no:
return account
f2 = Branch(123,"NY")
f2.account_list=[111,222,300005]
print(f2.getAccount(300005))
I am using eval to run a generated string to append the newly created EggOrder instance to the list of the correct instance of the DailyOrders class. The day provided by EggOrder is used to used to append to the correct instance. This relies on eval and the variable name of the DailyOrders instance and so it would be great to get this removed. I know there must be a better way.
class DailyOrders:
PRICE_PER_DOZEN = 6.5
def __init__(self, day):
self.orders = []
self.day = day
def total_eggs(self):
total_eggs = 0
for order in self.orders:
total_eggs += order.eggs
return total_eggs
def show_report(self):
if self.total_eggs() < 0:
print("No Orders")
else:
print(f"Summary:\nTotal Eggs Ordered: {self.total_eggs()}")
print(f"Average Eggs Per Customer: {self.total_eggs() / len(self.orders):.0f}\n*********")
class EggOrder():
def __init__(self, eggs=0, name="", day=""):
if not name:
self.new_order()
else:
self.name = name
self.eggs = eggs
self.day = day
eval(f"{self.day.lower()}.orders.append(self)")
def new_order(self):
self.name = string_checker("Name: ")
self.eggs = num_checker("Number of Eggs: ")
self.day = string_checker("Date: ")
def get_dozens(self):
if self.eggs % 12 != 0:
dozens = int(math.ceil(self.eggs / 12))
else:
dozens = self.eggs / 12
return dozens
def show_order(self):
print(f"{self.name} ordered {self.eggs} eggs. The price is ${self.get_dozens() * DailyOrders.PRICE_PER_DOZEN}.")
if __name__ == "__main__":
friday = DailyOrders("Friday")
friday_order = EggOrder(12, "Someone", "Friday")
friday_order.show_order()
friday.show_report()
saturday = DailyOrders("Saturday")
saturday_order = EggOrder(19, "Something", "Saturday")
saturday_order = EggOrder(27, "Alex Stiles", "Saturday")
saturday.show_report()
DailyOrders isn't actually a superclass (it was in a earlier version), it acts like one and I suspect the answer might have some inheritance.
I started learning python. Here is a simple program:
class StudentRepo:
def __init__(self):
self.student_list = []
def add(self, student):
self.student_list.append(student)
def get_list(self):
self.student_list
class Student:
def __init__(self, name, age):
self.age = age
self.name = name
from models.student.Student import Student
from services.student.StudentRepo import StudentRepo
s1 = Student("A", 10)
s2 = Student("B", 11)
# What is the issue here ?
StudentRepo.add(s1)
StudentRepo.add(s2)
studentList = StudentRepo.get_list()
for student in studentList:
print(student.name)
What is the issue with s1 = Student("A", 10) ?
There are two mistakes in your code. First, this:
def get_list(self):
self.student_list
should be:
def get_list(self):
return self.student_list
Second, you're using the class StudentRepo where you should be using an instance of StudentRepo:
s1 = Student("A", 10)
s2 = Student("B", 11)
my_roster = StudentRepo()
my_roster.add(s1)
my_roster.add(s2)
studentList = my_roster.get_list()
for student in studentList:
print(student.name)