0

I wrote some code and was not sure how to make it work as expected,

class Bee():
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier

bee = Bee(name='Bumble', identifier=1)
print(str(bee))

->> Should Print: 1 Bumble

I thought of creating a function in Class Bee as follows:

def get_hive(self):
    return '{} {}'.format(self.identifier, self.name)

However, I am not sure how, when I create an object of class Bee, to assign given attributes instead of address of the memory cell.

My code currently ofc prints smth like: <main.Bee object at 0x000001EA24F49460> instead of the attributes.

NoName
  • 21
  • 3
  • You just need to do `print(bee.get_hive())` – match Nov 24 '21 at 21:11
  • Why do you think it *should* print the attributes. Your aren't printing the attributes, you are printing *the object*. `bee` is a `bee` object. Why do you expect it to be anything else? *You wrote* `bee = Bee(name='Bumble', identifier=1)` – juanpa.arrivillaga Nov 24 '21 at 21:11
  • or use a `__str__` method that's the same as your proposed `get_hive` – Robin Zigmond Nov 24 '21 at 21:12
  • Also, after you implement `__repr__` and maybe `__str__` - there is no need to use `str()`. `print(bee)` will do – buran Nov 24 '21 at 21:14

1 Answers1

0

If you want str(bee) to return a string as you describe, implement a __str__ method:

class Bee():
    def __init__(self, name: str, identifier: int):
        self.name = name
        self.identifier = identifier

    def __str__(self) -> str:
        return f"{self.identifier} {self.name}"


bee = Bee('Bumble', 1)
print(bee)

prints:

1 Bumble

Note that print will automatically call str on any parameter that's not already a str, so you can just say print(bee) instead of print(str(bee)).

Samwise
  • 68,105
  • 3
  • 30
  • 44