Simple class Property Update - python

I have a class where I'm expecting this:
print(rithesh.amount) = 150.
How can I do this?
Here is my code:
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
def add_amount(self, amount):
self.amount = amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)

You can declare your amount variable in your __init__ method as 0. Then make a small change in your add_amount method.
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
self.amount = 0
def add_amount(self, amount):
self.amount += amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
output
150

The actual way of having properties in python is by using #property decorator
for example, in your class:
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
#property
def add_amount(self):
return self.add_amount
#add_amount.setter
def add_amount(self, amount):
self.add_amount = amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount = 150
print(rithesh.add_amount)

Got how to do it.
i have to declare the value self.amount = 0 during initialization.
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
self.amount = 0
def add_amount(self, amount):
self.amount += amount
rithesh = Customer("Ritehsh", "8892398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
hence getting output as print(rithesh.amount) = 150

What is happening is that when you call add_amount you are not adding the value to self.amount you are just setting it.
Just change the definition of add_amount from:
self.amount = amount
to:
self.amount += amount
And add to the __init__ method:
self.amount = 0

Related

java.lang.IllegalStateException: 2 members with a #ValueRangeProvider annotation must not have the same id (timeslotRangeLS)

Trying to generate school timetable with lab hours.
Kindly help me to solve this error! Thanks in advance.
Here is my code!
#planning_solution
class TimeTable:
timeslot_list: list[Timeslot]
timeslot_list1: list[Timeslot]
room_list: list[Room]
lesson_list: list[Lesson]
lab_list: list[Lab]
score: HardSoftScore
def __init__(self, timeslot_list, timeslot_list1, room_list, lesson_list,lab_list,
score=None):
self.timeslot_list = timeslot_list
self.timeslot_list1 = timeslot_list1
self.room_list = room_list
self.lesson_list = lesson_list
self.lab_list = lab_list
self.score = score
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLS")
def get_timeslot_list(self):
return self.timeslot_list
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLB")
def get_timeslot_list1(self):
return self.timeslot_list1
#problem_fact_collection_property(Room)
#value_range_provider("roomRange")
def get_room_list(self):
return self.room_list
#planning_entity_collection_property(Lesson)
def get_lesson_list(self):
return self.lesson_list
#planning_entity_collection_property(Lab)
def get_lab_list(self):
return self.Lab_list
#planning_score(HardSoftScore)
def get_score(self):
return self.score
def set_score(self, score):
self.score = score
def __str__(self):
return (
f"TimeTable("
f"timeslot_list={format_list(self.timeslot_list)},\n"
f"timeslot_list1={format_list(self.timeslot_list1)},\n"
f"room_list={format_list(self.room_list)},\n"
f"lesson_list={format_list(self.lesson_list)},\n"
f"lab_list={format_list(self.lab_list)},\n"
f"score={str(self.score.toString()) if self.score is not None else 'None'}"
f")"
)
Trying to get the 2 timeslots one for lesson(1 hour) and one for lab(2 hour).Here is my #planning_solution.
I defined 2 #planning_entity for both lab & lesson with #value_range_provider.
#planning_entity
class Lab(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot1: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot1 = None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot1 = timeslot1
self.room = room
#planning_variable(Base, value_range_provider_refs=['roomRange', 'timeslotRangeLB'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLB"])
def get_timeslot1(self):
return self.timeslot1
#value_range_provider(range_id = "timeslotRangeLB", value_range_type = Timeslot)
def get_possible_timeslot_list1(self):
return self.subject.teacher.student_group.room_list
def set_timeslot1(self, new_timeslot):
self.timeslot1 = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lab("
f"id={self.id}, "
f"timeslot1={self.timeslot1}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
#planning_entity
class Lesson(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot=None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot = timeslot
self.room = room
#planning_variable(Base, value_range_provider_refs=['timeslotRangeLS', 'roomRange'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLS"])
def get_timeslot(self):
return self.timeslot
#value_range_provider(range_id = "timeslotRangeLS", value_range_type = Timeslot)
def get_possible_timeslot_list(self):
return self.subject.teacher.student_group.room_list
# return self.course.teacher.department.room_list
def set_timeslot(self, new_timeslot):
self.timeslot = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lesson("
f"id={self.id}, "
f"timeslot={self.timeslot}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
The issue is you defined #value_range_provider(range_id = "timeslotRangeLS") on both your #planning_solution and your #planning_entity. You can only have one; if you want the value range to apply to every entity, do it on the #planning_solution. If you want each planning entity to have it own value range that only applies to it, do it on the #planning_entity. If you want to combine a value range that contains common values for all entities, and a value range that is per entity, use a #value_range_provider on the #planning_solution, and a #value_range_provider on the entity, but give them different ids (ex: #value_range_provider(range_id = "timeslotRangeLSSolution") and #value_range_provider(range_id = "timeslotRangeLSEntity"), and in the #planning_variable, use both range ids in the list (ex: #planning_variable(Room, ["timeslotRangeLSSolution", "timeslotRangeLSEntity"])

iterating objects in a list through a loop

So I'm just doing a learning project and I need some help.
class Car:
def __init__(self):
self.speed = 0
self.color = ""
self.weight = 0
self.engine = 4
self.name = ""
self.mpg = 25
self.maintenanceLog = []
self.oilChanges = []
#mutator methods
def setSpeed(self, sp):
self.speed = sp
def setColor(self, cl):
self.color = cl
def setWeight(self, w):
self.weight = w
def setEngine(self, e):
self.engine = e
def setName(self, n):
self.name = n
def setMpg(self, mpg):
self.mpg = mpg
def addOilChange(self, oc):
self.oilChanges.append(oc)
def addMaintenance(self, ml):
self.maintenanceLog.append(ml)
#accessor methods
def getSpeed(self):
return self.speed
def getColor(self):
return self.color
def getWeight(self):
return self.weight
def getEngine(self):
return self.engine
def getName(self):
return self.name
def getMPG(self):
return self.mpg
def getAllOilChanges(self):
print("")
print("----------OIL CHANGES----------")
for oc in self.oilChanges:
print(oc)
def getMaintenanceLogs(self):
print("")
print("----------MAINTENANCE LOGS----------")
for ml in self.maintenanceLog:
print(ml)
def setInfo(car):
car.setSpeed(int(input(f"Speed of {car}")))
car.setWeight(int(input(f"Weight of {car}")))
car.setName(input(f"Name of {car}"))
car.setColor(input(f"Color of {car}"))
car.setEngine(int(input(f"Engine of {car}")))
car.setMpg(int(input(f"Miles per Gallon of {car}")))
def getInfo(car):
print(f"Speed of {car} is {car.getSpeed()} mph.")
print(f"Weight of {car} is {car.getWeight()} pounds.")
print(f"Name of {car} is {car.getName()}.")
print(f"Color of {car} is {car.getColor()}.")
print(f"Engine cylinders of {car} are {car.getEngine()}.")
print(f"Miles per Gallon of {car} is {car.getMPG()}.")
def main():
carList = []
Object1= Car()
carList.append(Object1)
print(carList)
for obj in carList:
setInfo(obj)
getInfo(obj)
main()
Thats's the code, now, whenever I run it, I want to get asked Speed of Object1:
Instead, I get asked Speed of <main.Car object at 0x0000024B093CEFD0>:
How can I see the name of the object instead of that hash value... I want to keep adding objects with the class Car and then pass them through a loop to fill in the information regarding the object, but if the list of objects was [Object 1, Object 2, Object 3... Object N] I want it to refer to that name (Object 1) instead of <main.Car object at 0x0000024B093CEFD0>
You can pass the name to use in the prompts as an argument to setInfo().
def setInfo(car, name=None):
if name is None:
name = car.name
car.setSpeed(int(input(f"Speed of {name}")))
car.setWeight(int(input(f"Weight of {name}")))
car.setName(input(f"Name of {name}"))
car.setColor(input(f"Color of {name}"))
car.setEngine(int(input(f"Engine of {name}")))
car.setMpg(int(input(f"Miles per Gallon of {name}")))
and then use that in the loop.
for i, obj in enumerate(carList, 1):
setInfo(obj, f"Object {i}")
getInfo(obj)

NoneType object has no attribute

def forecast(bank, years):
class Bank:
def __init__(self, name):
self.name = name
self.mark_cap = 0
self.acc_list = []
self.age = 0
def lend(self, principal, ann_inc):
self.mark_cap -= principal
def forward_year(self):
self.age += 1
def back_year(self):
if self.age == 0:
self.age = 0
self.age -= 1
def show_high(self):
print(Bank.acc_list[0])
class Account:
def __init__(self, ID, password):
self.ID = ID
self.password = password
if len(password) < 5:
print('Password must be at least 5 characters')
self.amount = 0
self.interest = 0.0175
self.acc_org = [ID, password, self.amount, self.interest]
def deposit(self, x):
self.amount += x
self.acc_org[2] = self.amount
def withdraw(self, y):
self.amount -= y
self.acc_org[2] = self.amount
def threshold(self):
if self.amount >= 1000000:
self.interest = 0.02
def comp_int(self, n):
self.threshold()
self.amount *= (1 + self.interest)**n
self.acc_org[2] = self.amount
def show_amount(self):
print(self.amount)
def add_2_bank(self, name):
bank_name = name
bank_name.acc_list.append(self.acc_org)
X = Bank('Bank of china')
Account1 = Account('12345', '12345')
Account1.deposit(200)
Account1.comp_int(2)
Account1.add_2_bank(X)
X.show_high()
The error that I am getting is that my 'Bank' object (X) has no attribute acc_list(). Someone please help me.
In the show_high method, modify Bank.acc_list to self.acc_list. Only static properties can be used like Bank.*.

Multi level inheritance python - 'CheckingAccount' object has no attribute 'balance'

I am working on a python project. All was working well when I just had one level of inheritance but once I added SavingAccount and CheckingAccount which should be a child of BankAccount which is a child of Customer I started to get the following error: 'CheckingAccount' object has no attribute 'balance'
I assumed I would do the second layer of inheritance the same as the first but maybe I must be missing. Thanks in advance for any help!
class Customer:
def __init__(self,firstName, lastName, social):
self.firstName = firstName
self.lastName = lastName
self.social = social
def setfirstName(self,firstName):
self.firstName = firstName
def setlastName(self,lastName):
self.lastName = lastName
def __str__(self):
self.name = "{},{} (SSN:{})".format(self.firstName, self.lastName,self.social)
return self.name
class BankAccount(Customer):
from random import randint
n = 10
range_start = 10**(n-1)
range_end = (10**n)-1
accountNumber = randint(range_start, range_end)
def __init__(self,customer,balance = 0):
self.customer = customer
self.balance = balance
def setCustomer(self,customer,accountNumber):
self.customer = customer
self.accountNumber = accountNumber
def getCustomer(self,customer,accountNumber):
return self.customer, self.accountNumber
def deposit(self, amount):
self.balance = self.balance + amount
return self.balance
def withdrawal(self, amount):
self.balance = self.balance - amount
return self.balance
def __str__(self):
customer = "{} account number: {}, balance: ${}".format(self.customer,self.accountNumber,self.balance)
return customer
class CheckingAccount(BankAccount):
def __init__(self, bankAccount):
self.bankAccount = bankAccount
def applyAnnualInterest(self):
excess = self.balance - 10000
if excess > 0:
interest = (excess * .02)
self.balance = self.balance + interest
return self.balance
else:
return self.balance
class SavingAccount(BankAccount):
def __init__(self, bankAccount):
self.bankAccount = bankAccount
def applyAnnualInterest(self):
interest = (self.balance * .05)
self.balance = self.balance + interest
return self.balance
def main():
alin = Customer('Alin', 'Smith', '111-11-1111')
mary = Customer('Mary', 'Lee', '222-22-2222')
alinAccnt = CheckingAccount(alin)
maryAccnt = SavingAccount(mary)
alinAccnt.deposit(20000)
print(alinAccnt)
You need to initialise the parent; try:
class CheckingAccount(BankAccount):
def __init__(self, bankAccount):
super(CheckingAccount, self).__init__()
self.bankAccount = bankAccount
Don't forget the intermediate class too!
class BankAccount(Customer):
def __init__(self,customer,balance = 0):
super(BankAccount, self).__init__()
self.customer = customer
self.balance = balance
This will ensure the parent constructors get called too.

How to force the value on init?

I have defined following class of a bank account. The account should always start with 0.0 balance. How can I enforce that the value is always set 0.0 even if the user set it differently at the initiation?
class Account(object):
def __init__(self, name, balance=0.0):
self.name = name
self.balance = balance
def add_money(self, deposit_amnt):
self.balance += deposit_amnt
def withdraw_money(self, withdraw_amnt):
if withdraw_amnt > self.balance:
raise ValueError('Withdraw amount is more than balance')
else:
self.balance -= withdraw_amnt
def check_balance(self):
return self.balance
my_account = Account('Tim', 15)
my_account.check_balance()
>>> 15
You can ommit balance in __init__ if you want to start with 0. You have add method to do that later.
def __init__(self, name):
self.name = name
self.balance = 0

Categories

Resources