Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #29561
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: Fool Python class with imaginary members (serious guru stuff inside) |
| Date | 2012-09-20 13:04 -0400 |
| References | <89b80b56-d1f2-477e-b28a-4410f2cf9de6@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.966.1348160696.27098.python-list@python.org> (permalink) |
On 9/20/2012 9:52 AM, Jure Erznožnik wrote:
> I'm trying to create a class that would lie to the user that a member is in some cases a simple variable and in other cases a class. The nature of the member would depend on call syntax like so:
> 1. x = obj.member #x becomes the "simple" value contained in member
> 2. x = obj.member.another_member #x becomes the "simple" value contained in first member's another_member.
x.y.z is parsed and executed as (x.y).z, so you are asking if the
attribute-getter can know what will be done with the object it returns.
Assuming CPython, you would have to write something that searches the
Python code before compilation, the ast during compilation, or the
bytecode after compilation.
Much easier would be to define a union class that is a simple type with
attributes and return that in the first lookup.
class AttrInt(int):
def __getattr__(self, name): return 'attribute'
y = AttrInt(3)
print(y, y.a)
###
3 attribute
If x.y returns an AttrInt, it will act like an int for most purposes,
while x.y.z will return whatever AttrInt.__getattr__ does and the
temporary AttrInt y disappears.
--
Terry Jan Reedy
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Fool Python class with imaginary members (serious guru stuff inside) Jure Erznožnik <jure.erznoznik@gmail.com> - 2012-09-20 06:52 -0700 Re: Fool Python class with imaginary members (serious guru stuff inside) Terry Reedy <tjreedy@udel.edu> - 2012-09-20 13:04 -0400 Re: Fool Python class with imaginary members (serious guru stuff inside) Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-09-20 19:15 +0000
csiph-web