Python Forum

Full Version: adding properties to variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

The code below does exactly what I want. Basically the goal is to get an object, and then from that object, get some properties.
This is better explained with this example:

class Binary(object):

    def __init__(self, name):
        self._name = name

    def name(self):
        return self._name

    @property
    def asBinary(self):
        res = ''.join(format(i, 'b') for i in bytearray(self._name, encoding='utf-8'))
        return res

    def __repr__(self):
        return self.name()


class Person(object):

    def __init__(self, name):
        self._name = name

    def getName(self):
        binary = Binary(self._name)
        return binary


person = Person("Toby")
name = person.getName() # Result: Toby
name.asBinary  # Result: 1010100110111111000101111001
As I said, this works exactly as I want. I didn't want to have something like
person = Person("Toby")
person.getName()
person.getNameAsBinary  # <-- Don't want that. I want this --> name.asBinary
My question is just if there is a cleaner way to obtain the same result I got, or it is correct they way I did it.

thanks
R