Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading