473,786 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Property with parameter...

Hi !

I want to create a property that can use parameter(s).
In Delphi I can create same thing (exm: Canvas.Pixel[x,y] ->
Canvas.GetPixel (self,X,Y):inte ger; Canvas.SetPixel (self,X,Y,Color ::integer);

class A(object):
def __init__(self):
self.__Tags={}
def GetTag(self,tna me):
return self.__Tags.get (tname,None)
def SetTag(self,tna me,value):
self.__Tags[tname]=Value
Tag=property(Ge tTag,SetTag)

a=A()
print a.Tag('A')
print a.Tag['A']

But it is seems to be not possible in this way.

How to be can ?

Thanx for help !
KK
Jul 18 '05 #1
3 4111
kepes.krisztian <ke************ *@peto.hu> wrote:
Hi !

I want to create a property that can use parameter(s).
In Delphi I can create same thing (exm: Canvas.Pixel[x,y] ->
Canvas.GetPixel (self,X,Y):inte ger; Canvas.SetPixel (self,X,Y,Color ::integer);

class A(object):
def __init__(self):
self.__Tags={}
def GetTag(self,tna me):
return self.__Tags.get (tname,None)
def SetTag(self,tna me,value):
self.__Tags[tname]=Value
Tag=property(Ge tTag,SetTag)

a=A()
print a.Tag('A')
print a.Tag['A']

But it is seems to be not possible in this way.


Have your get method return an instance of an auxiliary class which
implements __getitem__ and __setitem__ (if you want to use square
brackets; if you want to use round parentheses, then __call__, but
beware -- you can't have a bare call on the left of an assignment!!!).

For example, a small refactoring of your attempt might be:

class A(object):

def __init__(self):
self.__Tags={}
self.__TagsAcce ssor = None

def getTagsAccessor (self):
if not self.__tagsAcce ssor:
def getter(__, tname):
return self.__Tags.get (tname, None)
def setter(__, tname, value):
self.__Tags[tname] = value
class TagAccessor: pass
TagAccessor.__g etitem__ = getter
TagAccessor.__s etitem__ = setter
self.__TagsAcce ssor = TagAccessor()
return self.__TagsAcce ssor
Tag = property(getTag sAccessor)

Now, you can use such code as:

a = A()
print a.Tag['foo']
a.Tag['foo'] = 'barbaz'
print a.Tag['foo']

Note that we define no setter at all for Tag. This means that, e.g.:

a.Tag = 23

will raise "AttributeError : can't set attribute". The way we coded,
a.Tag MUST be indexed when used on the left of an = sign in an
assignment. If that's not what you want -- if you do want to allow
assigning to bare a.Tag without an index -- then, and only then, write
a setTagsAccessor and give it whatever semantics you wish, and pass it
as the second argument in the call to property.

Of course, you can refactor this basic idea in many different ways. I
have used closures for getter and setter so as to finesse any trouble
with your use of leading double underscore, though that means that the
first argument of getter and setter CAN'T be named self (I used __ to
indicate I mean to ignore that argument...), but there are many other
possibilities, such as a more general TagAccessor class which takes
self.__Tags in its __init__, etc, etc. You could even choose to use a
custom descriptor class instead of the built-in property, but I don't
think that's warranted if all you need is what you have expressed.
Alex
Jul 18 '05 #2
On Mon, 13 Sep 2004 11:09:07 +0200, al*****@yahoo.c om (Alex Martelli) wrote:
kepes.krisztia n <ke************ *@peto.hu> wrote:
Hi !

I want to create a property that can use parameter(s).
In Delphi I can create same thing (exm: Canvas.Pixel[x,y] ->
Canvas.GetPixel (self,X,Y):inte ger; Canvas.SetPixel (self,X,Y,Color ::integer);

class A(object):
def __init__(self):
self.__Tags={}
def GetTag(self,tna me):
return self.__Tags.get (tname,None)
def SetTag(self,tna me,value):
self.__Tags[tname]=Value
Tag=property(Ge tTag,SetTag)

a=A()
print a.Tag('A')
print a.Tag['A']

But it is seems to be not possible in this way.
Have your get method return an instance of an auxiliary class which

Why a get method when a.Tag can return the aux class instance as a plain attribute?
(other than that the OP mentioned 'property' and might want to protect
against a.Tag = 23 ;-) E.g. See below.
implements __getitem__ and __setitem__ (if you want to use square
brackets; if you want to use round parentheses, then __call__, but
beware -- you can't have a bare call on the left of an assignment!!!).

For example, a small refactoring of your attempt might be:

class A(object):

def __init__(self):
self.__Tags={}
self.__TagsAcce ssor = None

def getTagsAccessor (self):
if not self.__tagsAcce ssor:
def getter(__, tname):
return self.__Tags.get (tname, None)
def setter(__, tname, value):
self.__Tags[tname] = value
class TagAccessor: pass
TagAccessor.__g etitem__ = getter
TagAccessor.__s etitem__ = setter
self.__TagsAcce ssor = TagAccessor()
return self.__TagsAcce ssor
Tag = property(getTag sAccessor)

Now, you can use such code as:

a = A()
print a.Tag['foo']
a.Tag['foo'] = 'barbaz'
print a.Tag['foo']

Note that we define no setter at all for Tag. This means that, e.g.:

a.Tag = 23

will raise "AttributeError : can't set attribute". The way we coded,
a.Tag MUST be indexed when used on the left of an = sign in an
assignment. If that's not what you want -- if you do want to allow
assigning to bare a.Tag without an index -- then, and only then, write
a setTagsAccessor and give it whatever semantics you wish, and pass it
as the second argument in the call to property.

Of course, you can refactor this basic idea in many different ways. I
have used closures for getter and setter so as to finesse any trouble
with your use of leading double underscore, though that means that the
first argument of getter and setter CAN'T be named self (I used __ to
indicate I mean to ignore that argument...), but there are many other
possibilitie s, such as a more general TagAccessor class which takes
self.__Tags in its __init__, etc, etc. You could even choose to use a
custom descriptor class instead of the built-in property, but I don't
think that's warranted if all you need is what you have expressed.

If the OP doesn't need to protect against a.Tag = 23 etc., seems like a
separate class for Tag might be simplest for him? I.e.,
class TagClass(object ): ... def __init__(self): self.__Tags = {}
... def __getitem__(sel f, k): return self.__Tags.get (k, None) # per OP
... def __setitem__(sel f, k, v): self.__Tags[k] = v
... class A(object): ... def __init__(self): self.Tag = TagClass()
...

Then a=A()
a.Tag[2,3] = 'two, three'
a.Tag[2,3] 'two, three' a.Tag <__main__.TagCl ass object at 0x00901210> vars(a) {'Tag': <__main__.TagCl ass object at 0x00901210>} vars(a.Tag)

{'_TagClass__Ta gs': {(2, 3): 'two, three'}}

For me, capitalized attributes kind of grate on the convention nerve though ;-)

Regards,
Bengt Richter
Jul 18 '05 #3
Bengt Richter <bo**@oz.net> wrote:
...
Have your get method return an instance of an auxiliary class which Why a get method when a.Tag can return the aux class instance as a plain
attribute? (other than that the OP mentioned 'property' and might want to
protect against a.Tag = 23 ;-) E.g. See below.


Yes, if the OP is happy about potentially letting client code trample
over his precious a.Tag by assigning to it, and further is happy having
every instance of class A instantiating and holding an instance of a
Tags class (rather than doing it just-in-time if and when that attribute
is accessed) -- briefly, if he needs none of the advantages afforded by
properties -- then he'd be best advised to avoid using properties.

If the OP doesn't need to protect against a.Tag = 23 etc., seems like a
separate class for Tag might be simplest for him? I.e.,
>>> class TagClass(object ): ... def __init__(self): self.__Tags = {}
... def __getitem__(sel f, k): return self.__Tags.get (k, None) # per OP
... def __setitem__(sel f, k, v): self.__Tags[k] = v
... >>> class A(object):
... def __init__(self): self.Tag = TagClass()


If instances of class A need no other access to the dictionary than that
afforded to other code by the get/set-item special methods of this class
TagClass (in addition to not needing any of the potential extras of
properties), then this factoring (giving the TagClass instance whole
responsibility for handling the dict) may indeed be optimal. More
usually, though, the coupling may usefully be closer -- and I mentioned
some other factorings that would afford that, besides the unusual one I
showed in detail which used closures to effect the coupling.
For me, capitalized attributes kind of grate on the convention nerve

though ;-)

It's not a common convention in Python practice, agreed. Not unheard
of, though -- I do believe it's mentioned in the style PEP, isn't it?
Alex
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1952
by: Aaron | last post by:
Hi, I've seen javascript code where a constructor function is passed an argument "document", and inside the function itself the assignment "this.document = document;" is made. This is the code (or the part necessary for the example): function ToggleButton(document) { ToggleButton.images = new Array(4); for(i=0;i<4;i++) { ToggleButton.images = new
1
1710
by: Heather | last post by:
How is the Parameter property for menu items used? Thanks! Heather
4
2487
by: Roberto Sartori | last post by:
Hi. I'd want to know if it is possible in C # to declare one property analogous to following (written in VB): Property PropertyName (ByVal Index As Integer) As Object Get Return List.Item(Index) End Get Set (ByVal Value As Object)
1
8437
by: Andy G | last post by:
I've been getting this error all day. Could someone please look at my stored procedure and the code. I have a form that grabs and email address the user types in, calls a stored procedure with an input parameter and an output parameter, compared the email to a table and matches an ID in another table to grab the Username. thanks for any helps guys/girls! Andy :)
6
9069
by: Cc | last post by:
hi, is there a way to use byref on property set , because i would like to pass the value into the variable byref ?
4
4040
by: Pritcham | last post by:
Hi all I've got a number of classes already developed (basic entity classes) like the following: Public Class Contact Private _firstname as String Private _age as Integer Public Property FirstName As String
1
1317
by: yeltsin27 | last post by:
I can see how to use a cookie, control property, form input value, profile, query string or session value as a parameter to a SQL Data Source. However I would like to use a property that is declared on the page (which as it happens is persised in VIEWSTATE). I know I could write the property to a control, but that's no different to writing the value to the ControlParameter, which is what I'm doing now.
0
6992
by: Bryce Fischer | last post by:
I've got a simple (I think) asp.net application. I've created a DataSet in App_Code/ItemDataSet.xsd. Tested connection, seemed to work fine. In my ASPX file, I first dropped an ObjectDataSource onto the form, and pointed it to the dataset created above. I then dropped a GridView on the form, and selected the ObjectDataSource I created above. In the Design view it seems to be at least loading the
3
1967
by: Peter Gast | last post by:
Hi, I need as a parameter for a control the names of my properties as a string. How can I get the name of the property as a string during runtime Example: Private _MyVar As Double Public ReadOnly Property MyVar As Double Get Return _MyVar End Get
7
1368
by: Andy B | last post by:
I saw this in the set accessor of a property: Set(ByVal value As DataSet) What exactly does the stuff in the () mean? VS complained about it not being there when I took it out not knowing it needed to be there.
0
9497
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4067
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.