Python Forum
adding properties to variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
adding properties to variables
#1
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  variables vcnt, ocnt, and mcnt adding previous values and not resetting to 0 archanut 2 653 Feb-12-2021, 06:56 PM
Last Post: deanhystad
  API design question: use methods or properties? johsmi96 1 614 Oct-12-2020, 02:24 PM
Last Post: buran
  Create a 3D volume with some properties. Rosendo 0 622 Jul-18-2020, 08:20 PM
Last Post: Rosendo
  printing class properties from numpy.ndarrays of objects pjfarley3 2 911 Jun-08-2020, 05:30 AM
Last Post: pjfarley3
  Adding markers to Folium map only adding last element. tantony 0 1,093 Oct-16-2019, 03:28 PM
Last Post: tantony
  Adding Variables absolum 3 1,396 Jul-18-2019, 12:32 PM
Last Post: absolum
  iterate over class properties? NobahdiAtoll 10 4,469 Aug-26-2018, 08:43 PM
Last Post: NobahdiAtoll
  Advance properties read from xml files python1234 0 1,336 Apr-25-2018, 01:42 PM
Last Post: python1234

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020