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))
Related
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 am still learning Python and I have a problem. If my question isn't that clear, please be nice!
Is it possible that while using a list, I can delete an object from the list if only one object matches
So for example:
driver.addDriver(Driver("Ben", "BBB"))
driver.removeDriver("Ben", "123")
Can I remove the driver name and print as None while still showing the vehicle number. Thanks.
class Driver:
def __init__(self, name, vehNo):
self._name = name
self._vehNo = vehNo
#property
def name(self):
return self._name
#property
def vehNo(self):
return self._vehNo
#vehNo.setter
def vehNo(self, newVehNo):
self._vehNo = newVehNo
def __str__(self):
return 'Driver Name: {} Vehicle Number: {}'.format(self._name, self._vehNo)
class TransportServices:
def __init__(self):
self._drivers = []
def searchDriver(self, name = None, vehNo = None):
for d in self._drivers:
if d.name == name and d.vehNo == vehNo:
return d
return None
#############################################################################
def addDriver(self, driver):
d = self.searchDriver(driver.name)
if d is None:
self._drivers.append(driver)
return True
else:
return False
#############################################################################
def removeDriver(self, name = None, vehNo = None):
d = self.searchDriver(name, vehNo)
if d is None:
return False
else:
self._drivers.remove(d)
#############################################################################
def __str__(self):
drivers = [str(d) for d in self._drivers]
return "{} ".format('\n'.join(drivers))
def main():
driver = TransportServices()
driver.addDriver(Driver("Alan", "AAA"))
driver.addDriver(Driver("Ben", "BBB"))
driver.removeDriver("Ben", "123")
print(driver)
main()
Basically what you are looking for is not deleting the object but updating it.
You can update the corresponding object as below:
for driver in self.drivers:
if driver.name == 'Bob': # or driver vehNo == 'BBB'
driver.name = None
Also for your case,
you could rather use a dictionary which is the same
as a hash map in Java.
You can do some thing like below:
self.drivers = {}
self.driver['vehicle Num'] = theDriverObject
so that when you need to access or update you can do it instantly i.e. O(1) without having to loop through all the drivers.
I have a class "PushInfo"
And generate 300 PushInfo object in list
I want remove duplicate userid and ip in the list
Here is my code:
from faker import Faker
import random
def RemovePustListDuplicateData(PushList):
return list(set([(x.userid, x.ip) for x in PushList]))
def FakeData(number):
PushList = []
fake = Faker()
accountList = [('john','127.0.0.1'),('john','127.0.0.1'),('amy','127.0.0.1'),
('lia','140.112.1.9'),('julia','140.112.1.9'),
('asuka','140.112.1.9'),('roy','140.112.1.9'),('stacie','140.112.1.9'),('ben','123.964.123.41'),
('yich','127.0.0.1'),('beef','127.0.0.1'),('aloha','235.151.123.1'),('yamaha','235.151.123.1')]
for i in range(0,number):
user = random.choice(accountList)
PushList.append(PushInfo(fake.name(),
user[0],
fake.text(max_nb_chars=10),
fake.date(pattern="%Y-%m-%d"),
user[1]
))
return PushList
class PushInfo:
def __init__(self, name, userid, content, time,ip=''):
self.name = name
self.userid = userid
self.content = content
self.time = time
self.ip = ip
PushList = FakeData(300)
print("top 10 push in list:")
for push in PushList[:10]:
print("name:"+push.name+" id:"+push.userid+" content:"+push.content+" time:"+push.time+" ip:"+push.ip)
print("\nremove duplicate userid and ip data")
print(RemovePustListDuplicateData(PushList))
https://repl.it/#YichLin/Remove-object-in-list/
The example code is return tuple list
[(userid,ip),(userid,ip)....]
But the result I want is
[PushInfo(some data),PushInfo(some data),.....]
How to achieve this result?
Try this:
from faker import Faker
import random
def RemovePustListDuplicateData(PushList):
return list(set(PushList))
def FakeData(number):
PushList = []
fake = Faker()
accountList = [('john','127.0.0.1'),('john','127.0.0.1'),('amy','127.0.0.1'),
('lia','140.112.1.9'),('julia','140.112.1.9'),
('asuka','140.112.1.9'),('roy','140.112.1.9'),('stacie','140.112.1.9'),('ben','123.964.123.41'),
('yich','127.0.0.1'),('beef','127.0.0.1'),('aloha','235.151.123.1'),('yamaha','235.151.123.1')]
for i in range(0,number):
user = random.choice(accountList)
PushList.append(PushInfo(fake.name(),
user[0],
fake.text(max_nb_chars=10),
fake.date(pattern="%Y-%m-%d"),
user[1]
))
return PushList
class PushInfo:
def __init__(self, name, userid, content, time,ip=''):
self.name = name
self.userid = userid
self.content = content
self.time = time
self.ip = ip
def __eq__(self, other):
return self.userid==other.userid and self.ip==other.ip
def __hash__(self):
return hash(('userid', self.userid, 'ip', self.ip))
def __repr__(self):
return str(self.userid) + ' ' + str(self.ip)
PushList = FakeData(300)
print("top 10 push in list:")
for push in PushList[:10]:
print("name:"+push.name+" id:"+push.userid+" content:"+push.content+" time:"+push.time+" ip:"+push.ip)
print("\nremove duplicate userid and ip data")
print(RemovePustListDuplicateData(PushList))
You need to implement eq and hash methods in order to check whether two objects are same.
Change the RemovePustListDuplicateData(PushList) function as follows:-
def RemovePustListDuplicateData(PushList):
object_memo = set()
final_list = []
for object in PushList:
if (object.userid, object.ip) in object_memo:
continue
else:
final_list.append(object)
object_memo.add((object.userid, object.ip))
return final_list
I hope it helps!
I have a class Node with a function defined
class Node(object):
def __init__(self, index, state = None, input = None, directed_neighbours=False):
"""
Parameters
----------
index : int
Node index. Must be unique in the graph.
"""
self._input = input
self.state = state
#self._status = 'active'
self._index = int(index)
self._neighbours = set()
self._port_count = 0
self._ports = []
if directed_neighbours:
self._predecessors = set()
self._successors = self._neighbours
self._directed_neighbours = True
else:
self._successors = self._neighbours
self._predecessors = self._neighbours
self._directed_neighbours = False
#property
def setStatus(self, status):
self._status = status
I have another function
def init(node):
node.setStatus('active')
Now, I have a class
class DistAlgo:
def __init__(self, name, initFunc, states, messages, sendFunc, receiveFunc, stoppingCheck):
self.name = name
#self.inputGraph = inputGraph
self.initFunc = initFunc
self.states = states
self.messages = messages
self.sendFunc = sendFunc
self.receiveFunc = receiveFunc
self.comm_round = 0
self.stoppingCheck = stoppingCheck
def run(self, inputGraph):
for node in inputGraph.nodes:
print('hello', node)
node.state = self.initFunc(node)
<....more code...>
When I create an object of DistAlgo
myalgo = DistAlgo('BMM', init, states, messages, send, receive, stoppingCheck)
and then call its run function:
myalgo.run(problemGraph)
I get an error in the init function above, as:
TypeError: setStatus() missing 1 required positional argument: 'status'
I surely am doing more than one thing wrong I guess, as this is my first Python try. Please point them out!
Properties work a bit differently:
#property
def status(self):
return self._status
#status.setter
def status(self, status):
self._status = status
Now you can set the value with an assignment:
node.status = 'active'
I need some help understanding python scoping with classes.
For instance this is a perfectly valid program, which makes sense to me
import json
class Person(object):
def __init__(self, firstname, lastname, age,address):
self.firstname = firstname
self.age = age
self.lastname = lastname
self.address = address
class Address(object):
def __init__(self,zipcode,state):
self.zipcode = zipcode
self.state = state
personlist = []
for count in range(5):
address = Address("41111","statename")
person = Person("test","test",21,address)
print(count)
personlist.append(person)
jsonlist = []
for Person in personlist:
print Person.firstname
d = {}
d['firstname'] = Person.firstname
d['lastname'] = Person.lastname
d['age'] = Person.age
d['zipcode'] = Person.address.zipcode
d['state'] = Person.address.state
jsonlist.append(d)
jsondict = {}
jsondict["People"] = jsonlist
jsondict["success"] = 1
json_data = json.dumps(jsondict, indent =4)
print json_data
But this next program gives me an error
import json
class Person(object):
def __init__(self, firstname, lastname, age,address):
self.firstname = firstname
self.age = age
self.lastname = lastname
self.address = address
class Address(object):
def __init__(self,zipcode,state):
self.zipcode = zipcode
self.state = state
def main():
personlist = []
for count in range(5):
address = Address("41111","statename")
person = Person("test","test",21,address)
print(count)
personlist.append(person)
jsonlist = []
for Person in personlist:
print Person.firstname
d = {}
d['firstname'] = Person.firstname
d['lastname'] = Person.lastname
d['age'] = Person.age
d['zipcode'] = Person.address.zipcode
d['state'] = Person.address.state
jsonlist.append(d)
jsondict = {}
jsondict["People"] = jsonlist
jsondict["success"] = 1
json_data = json.dumps(jsondict, indent =4)
print json_data
main()
My question is why creating the classes in white space valid but creating them inside a function not valid. Is there any way to create them in the main function and it be valid?
EDIT:
Error is
File "jsontest.py", line 9, in main
person = Person("test","test",21,address)
UnboundLocalError: local variable 'Person' referenced before assignment
The problem is that you use a variable with the same name as your class Person (also called "shadowing"):
for Person in personlist:
Python detects that you use it as a local variable and raises an error:
UnboundLocalError: local variable 'Person' referenced before
assignment
which means that you try to use a local variable before it was assigned in the following line:
person = Person("test","test",21,address)
You can find more information about it here