473,408 Members | 2,025 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Setting up properties from the __init__ method

I have gotten properties to respond correctly, but
when I try to do it in __init__:

class foo:

def getter(self):
return "hello"
def __init__(self):
self.prop = property(self.getter)

bar = foo()
print bar.prop
print bar.prop.fget()
I get:

<property object at 0x815a05c>
hello
So is saying self.attr in the __ini__ method different
than just saying attr=value right in the class definition?
Assigning a the return of property() behaves clearly differently
in each case.

Thanks,

Toby

Jul 18 '05 #1
3 1977
On Thu, Oct 30, 2003 at 12:22:09AM +0000, us**@domain.invalid wrote:

So is saying self.attr in the __ini__ method different
than just saying attr=value right in the class definition?
Yes; assigning to self.attr in a method (such as __init__) will set that
attribute on the instance, but assigning in the class definition will set
that attribute on the class.
Assigning a the return of property() behaves clearly differently
in each case.


Descriptors (such as properties) need to be set on a class to work their
magic. Instances don't check their attributes for __get__/__set__/__del__
magic methods when accessing them, but classes do.

(This question pops up fairly regularly, and it's not obvious to new users
what's going on... perhaps there should be a FAQ entry about why
per-instance properties don't work?)

-Andrew.
Jul 18 '05 #2
On Thu, 30 Oct 2003 11:48:10 +1100, Andrew Bennetts <an***************@puzzling.org> wrote:
On Thu, Oct 30, 2003 at 12:22:09AM +0000, us**@domain.invalid wrote:

So is saying self.attr in the __ini__ method different
than just saying attr=value right in the class definition?
Yes; assigning to self.attr in a method (such as __init__) will set that
attribute on the instance, but assigning in the class definition will set
that attribute on the class.

Unless it happens to be defined in the class as a property, in which case that
will be triggered ;-) (BTW, you can use that to good effect in an __init__ or
other method to access a property consistently from everywhere. See example, where
the __init__ accesses the self.prop both ways.
Assigning a the return of property() behaves clearly differently
in each case.


Descriptors (such as properties) need to be set on a class to work their
magic. Instances don't check their attributes for __get__/__set__/__del__
magic methods when accessing them, but classes do.

(This question pops up fairly regularly, and it's not obvious to new users
what's going on... perhaps there should be a FAQ entry about why
per-instance properties don't work?)

You can program a normal property to delegate to instance-specific stuff though, so you
could fake it pretty well if you put your mind to it ;-) The question would be WTHeck you
were trying to do with that kind of design. Ok, we won't break our toys, but we can mess
with them a little to see how they work, e.g.,
class Foo(object): ... def getprop(self):
... instprop = vars(self).get('prop')
... if instprop: return instprop.fget(self)
... return '%r from getprop'%self._prop
... def setprop(self, v): self._prop=v
... prop = property(getprop, setprop)
... def __init__(self):
... self.prop = '<initial prop value>' # note that this goes via setprop to self._prop
... def instgetprop(self): return '%r from instgetprop'%self._prop
... self.__dict__['prop'] = property(instgetprop) # self.prop would trigger setprop
... foo = Foo()
foo.prop "'<initial prop value>' from instgetprop"

Note that the above is deferring to the instance-attribute-defined prop
foo.prop = 123
foo.prop '123 from instgetprop'

.... still doing it. Now we'll get rid of the instance attribute named prop
del foo.prop # can't get rid of instance property this way Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't delete attribute

That exception was because the property intercepts get set and del, and we didn't
define the latter property function.
del foo.__dict__['prop'] # this way doesn't trigger class-defined prop
Ok, now to access prop without the instance attribute, so the real prop (which always
gets control) doesn't see anything to defer to:
foo.prop '123 from getprop'

QED
foo.prop = 456
foo.prop '456 from getprop'

Now if we re-establish the instance prop by re-executing __init__:
foo.__init__ <bound method Foo.__init__ of <__main__.Foo object at 0x009010F0>> foo.__init__()
We get the delegated effect (that we programmed the real prop to do) again
foo.prop "'<initial prop value>' from instgetprop" foo.prop = 789
foo.prop

'789 from instgetprop'

You could do much more generalized stuff along the same lines, intercepting any attribute
name and checking for an "instance property" also. Only your imagination (and possibly backlash
from your code maintenance heirs ;-) sets the limits.

This sort of stuff is not recommended for ordinary use, but it's nice to know you can do
about anything you want with Python if you have a real need.
However, most such "needs" are probably mistaken ;-)

Regards,
Bengt Richter
Jul 18 '05 #3
us**@domain.invalid writes:
I have gotten properties to respond correctly, but
when I try to do it in __init__:

class foo:


Note in addition to the replies you got, the world of descriptors only
applies in fullness to new-style types -- so

class foo(object):

would be a better start.

Cheers,
mwh

--
<arigo> something happens, what I'm not exactly sure.
-- PyPy debugging fun
Jul 18 '05 #4

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

Similar topics

0
by: Peter Dobcsanyi | last post by:
Hi, I reworked a few methods of a class using properties but then realized that the online help in interactive sessions would not work as I expected. The reason is the way how doc strings of...
18
by: Dixie | last post by:
Can I set the Format property in a date/time field in code? Can I set the Input Mask in a date/time field in code? Can I set the Format of a Yes/No field to Checkbox in code? I am working on...
1
by: Pierre | last post by:
Folks, I'm pretty new to OOP, so I still have problems with inheritance and delegation. I defined 2 Numeric MaskedArray subclasses, as: class Temp(MA,object): def __init__(self,data): self =...
3
by: redefined.horizons | last post by:
I've been reading about Python Classes, and I'm a little confused about how Python stores the state of an object. I was hoping for some help. I realize that you can't create an empty place holder...
2
by: Francesco Guerrieri | last post by:
Hello, this is my first post to the list :-) I've looked around a bit before asking, and since I haven't found... I'm here to ask my question. I'm trying to ovveride attribute setting, but I...
17
by: David C. Ullrich | last post by:
Having a hard time phrasing this in the form of a question... The other day I saw a thread where someone asked about overrideable properties and nobody offered the advice that properties are...
1
by: rowland | last post by:
I'm trying to come up with solution for adding synthetic properties to python, similar to synthetic properties in Objective-C. I'm playing around with doing this in a MetaClass. I can...
4
by: mk | last post by:
Hello everyone, I try to set two properties, "value" and "square" in the following code, and arrange it in such way that setting one property also sets another one and vice versa. But the code...
0
by: Maric Michaud | last post by:
Le Wednesday 03 September 2008 15:57:50 mk, vous avez écrit : Your square property is not correctly defined, it recurselively call itself, it should be (I also avoided the extra lookup) : def...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.