Home > Enterprise >  Appending to list within class and getting an accurate len()
Appending to list within class and getting an accurate len()

Time:03-09

I have a way to make this work, using the def get_count method. What I am wondering is, why can I not get self.size to populate accurately below the class init, while everything else will populate at that location.

Goal is to append members to the instance, and then get the size to reflect the count of members added. Try to run the last line, case_one.show_all() , and you will get the a 0 where self.size is printing.

Is there a reason this is the case or a way around it besides a separate method? Thanks

class Accounting:
    def __init__(self, number, pencils):
        self.number = number
        self.pencils = pencils
        self.members = []
        self.size = len(self.members)

        # self.pencil_count = self.pencils / self.size #failing due to self.size not populating correctly

    def show_all(self):
        print(self.number)
        print(self.pencils)
        print(self.members)
        print(self.size)

    def get_count(self):
        print(len(self.members))


case_one = Accounting(1, 7)
case_one.members.append("Bob")
case_one.members.append("Jane")

# print(len(case_one.members))

case_one.get_count()

# case_one.show_all()

CodePudding user response:

An easy solution is to make self.size a property. I.e. instead of defining a size attribute in your __init__:

        self.size = len(self.members)

define a size method and make it a @property:

    @property
    def size(self) -> int:
        return len(self.members)

Now any time you access self.size, you will actually get the current (not previously cached) value of len(self.members).

  • Related