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
  PDF properties doesn't show created or modified date Pedroski55 4 1,094 Jun-19-2023, 08:09 AM
Last Post: Pedroski55
  File path by adding various variables Mishal0488 2 1,038 Apr-28-2023, 07:17 PM
Last Post: deanhystad
  How do I list properties quarinteen 0 1,056 May-01-2022, 04:15 PM
Last Post: quarinteen
  variables vcnt, ocnt, and mcnt adding previous values and not resetting to 0 archanut 2 1,937 Feb-12-2021, 06:56 PM
Last Post: deanhystad
  API design question: use methods or properties? johsmi96 1 1,685 Oct-12-2020, 02:24 PM
Last Post: buran
  Create a 3D volume with some properties. Rosendo 0 1,426 Jul-18-2020, 08:20 PM
Last Post: Rosendo
  printing class properties from numpy.ndarrays of objects pjfarley3 2 1,956 Jun-08-2020, 05:30 AM
Last Post: pjfarley3
  Adding markers to Folium map only adding last element. tantony 0 2,125 Oct-16-2019, 03:28 PM
Last Post: tantony
  Adding Variables absolum 3 2,530 Jul-18-2019, 12:32 PM
Last Post: absolum
  iterate over class properties? NobahdiAtoll 10 10,076 Aug-26-2018, 08:43 PM
Last Post: NobahdiAtoll

Forum Jump:

User Panel Messages

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