-1

I am doing a course project based on Python and I am curious if there is a way to write something similar to this (written in C++) in python. I am struggling to write this in Python (transfer information from text file into the set/getters of a class I have already created.

while (file >> Code >> Name >> Description >> Price >> Quantity >> color >> 
            Size >> BasketballRate) {
    Basketball* object3 = new Basketball();
    object3->SetName(Name);
    object3->SetCode(Code);
    object3->SetDescript(Description);
    object3->SetPrice(Price);
    object3->SetQuantity(Quantity);
    object3->setColor(color);
    object3->setSize(Size);
    object3->setBasketballRate(BasketballRate);
    basketball.push_back(object3);
}
file.close();
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    It is helpful to all if you add a short (better) description of your goal. [How to ask a question on SO](https://stackoverflow.com/help/how-to-ask) – mccurcio Mar 29 '21 at 17:26
  • 1
    Welcome to Stack Overflow! Please take the [tour] and read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/4518341) What have you already tried, and where are you stuck exactly? For example, do you know how to read from a file? Do you know how to instantiate a class? What does the class look like? Also, I don't know C++, so the code you provided doesn't help much. FWIW, [if you're writing setters and getters in Python, you're probably doing something wrong](https://stackoverflow.com/a/36943813/4518341). See [ask] if you want more tips. – wjandrea Mar 29 '21 at 17:30

1 Answers1

0

Getters and setters typically aren't used in Python since they're seldom needed and can effectively be added latter (without breaking existing code) if there turns out to be some unusual reason to have one or more of them.

Here's an example of reading the data from a text file and using it to create instances of the Basketball class.

class Basketball:
    fields = ('name', 'code', 'description', 'price', 'quantity', 'color', 'size',
              'basketball_rate')

    def __init__(self):
        for field in type(self).fields:
            setattr(self, field, None)

    def __str__(self):
        args = []
        for field in type(self).fields:
            args.append(f'{field}={getattr(self, field)}')
        return f'{type(self).__name__}(' + ', '.join(args) + ')'


basketballs = []
with open('bb_info.txt') as file:
    while True:
        basketball = Basketball()
        try:
            for field in Basketball.fields:
                setattr(basketball, field, next(file).rstrip())
        except StopIteration:
            break  # End of file.
        basketballs.append(basketball)


for basketball in basketballs:
    print(basketball)
martineau
  • 119,623
  • 25
  • 170
  • 301