Home > Net >  How do i access all values of a particular instance variable in python class
How do i access all values of a particular instance variable in python class

Time:08-03

I'm practicing OOP in python and I'm trying to rewrite my code using class. Each instance in the class is meant to have a unique value for a particular instance variable. So I need to check to see if the value that is to be assigned is not being used by another instance before assigning.

So for example, how do i convert something like this using class.

from random import randint

accounts = {}
acc_number = []

names = ['john','ambrose','jess']
for name in names:
    acc_num = randint(1,10)
    while True:
        if acc_num in acc_number:
            acc_num = randint(1,10)
        else:
            acc_number.append(acc_num)
            break
    accounts[name] = acc_num
print(accounts)

Since the purpose of class is to keep each instance's values apart, how can I neatly ensure acc_numberis unique?

CodePudding user response:

are you talking about how to make a class that's guaranteed to have a unique attribute named acc_num?

used_acc_nums = []    

class Account:
    def __init__(self,name):
        self.name = name

        self.acc_num = random.randint(0,10)

        while self.acc_num in used_acc_nums:
            self.acc_num = random.randint(0,10)

        used_acc_nums.append(self.acc_num)

john = Account("John")
ambrose = Account("Ambrose")
jess = Account("Jess")

for acc in [john, ambrose,jess]:
    print(acc.name , acc.acc_num)

CodePudding user response:

Could have something like this:

from random import choice


class Person:
    def __init__(self):
        self.id = list(range(1, 10))
        self.accounts = {}

    def assign(self, name):
        get_id = choice(self.id)
        self.id.remove(get_id)
        self.accounts[name] = get_id

    def accounts(self):
        return self.accounts


person = Person()
people = ['john', 'ambrose', 'jess']

for p in people:
    person.assign(p)

print(person.accounts)

>>> {'john': 6, 'ambrose': 8, 'jess': 7}
  • Related