473,324 Members | 2,268 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,324 software developers and data experts.

sub typing built in type with common attributes. Am I right?

I am new to python and getting into classes. Here I am trying to
create subtype of built in types with some additional attributes and
function. 'Attributes' is the main class and holds all the common
attributes that requires by these subtypes. This is what I came out
with. I need to know whether everything is right here ? or there are
some better ways to do it.

class Attribute(object):
"""
Common attributes and methods for custom types
"""

def __init__(self, name=None, type=None, range=None, label=None):

#read only attributes
self._name = name
self._type = type
self._range = range

#read/write attribute
self.label = label

#make read only attributes
name = property(lambda self: self._name)
type = property(lambda self: self._type)
range = property(lambda self: self._range)

class Float(float, Attribute):

'''Custom Float class with some additional attributes.'''

__slots__ = ['_Attribute__name', '_Attribute__type',
'_Attribute__range', 'label']

def __new__(cls, value=0.0, *args, **kwargs):
return float.__new__(cls, value)

def __init__(self, value=0.0, name=None, label=None, type=None,
range=(0.0, 1.0)):
super(Float, self).__init__(name=name, label=label, type=type,
range=range)

def __str__(self):
return '{ %s }' % (float.__str__(self))

class Int(int, Attribute):

'''Custom Int class with some additional attributes.'''

__slots__ = ['_Attribute__name', '_Attribute__type',
'_Attribute__range', 'label']

def __new__(cls, value=0.0, *args, **kwargs):
return int.__new__(cls, value)

def __init__(self, value=0.0, name=None, label=None, type=None,
range=(0.0, 1.0)):
super(Int, self).__init__(name=name, label=label, type=type,
range=range)

def __str__(self):
return '{ %s }' % (int.__str__(self))
Jul 18 '08 #1
5 1129
King wrote:
I am new to python and getting into classes. Here I am trying to
create subtype of built in types with some additional attributes and
function. 'Attributes' is the main class and holds all the common
attributes that requires by these subtypes. This is what I came out
with. I need to know whether everything is right here ? or there are
some better ways to do it.
There may be some technical errors in your code, e. g.

- the __slots__ look like a bit of bullshit: you already have a __dict__
from the Attribute base class
- name mangling is done for attributes starting with two underscores

But the greater problem I see is that you are building up a huge bureaucracy
where pythonic code would concentrate on a concrete goal with minimal
administrative overhead.

Peter

Jul 18 '08 #2
My mistake...
The correct __slots__ is like:
__slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range',
'label']

Could you please suggest an alternative or code improvement for the
matter.

Prashant
Jul 18 '08 #3
King wrote:
My mistake...
The correct __slots__ is like:
__slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range',
'label']

Could you please suggest an alternative or code improvement for the
matter.
How about

class AttributesMixin(object):
"""Warning: If you change name, type, or range of an existing object
your computer will explode and you will have noone else to blame.
"""
def __init__(self, name=None, type=None, range=None, label=None):
self.name = name
self.type = type
self.range = range
self.label = label

class Float(float, AttributesMixin): pass
class Int(int, AttributesMixin): pass

Now go and write something useful :-)

Peter
Jul 18 '08 #4
Le Friday 18 July 2008 11:36:20 King, vous avez écrit*:
Could you please suggest an alternative or code improvement for the
matter.
I'm not sure what you are trying to achieve with your snippet, but I suspect
it's some sort of templating, right ? If so, using the dynamic nature of
python should help :
>>>[103]: def make_subtype_with_attr(type_, ro_attr, rw_attr) :
dic = {}
for i in ro_attr : dic[i] = property(lambda s, n=i : getattr(s, '_'+n))
def __new__(cls, *args, **kwargs) :
instance = type_.__new__(cls, *args)
for i in rw_attr : setattr(instance, i, kwargs[i])
for i in ro_attr : setattr(instance, '_'+i, ro_attr[i])
return instance
dic['__new__'] = __new__
return type('my_' + type_.__name__, (type_,), dic)
.....:
>>>[113]: my_int = make_subtype_with_attr(int,
{'name' : 'myint', 'id':123452}, ('foo',))
>>>[114]: i = my_int(5, foo=3)
>>>[115]: i.foo
...[115]: 3
>>>[116]: i
...[116]: 5
>>>[117]: i.id
...[117]: 123452
>>>[118]: i.id = 2
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)

/home/maric/<ipython consolein <module>()

AttributeError: can't set attribute
--
_____________

Maric Michaud
Jul 18 '08 #5
Thanks Michaud,

You have actually solved an another problem by
'make_subtype_with_attr' function.

What actually I am trying to do here is to create custom types using
built in types to use in my application.
For example , float2, float3, color, vector, point, normal, matrix
etc. The reason being creating as individual subtypes is because each
subtypes has it's own set of functions as well as common functions and
attributes defined in 'Attribute' class.

Although I won't be doing any math using subtypes like multiply a
color by another color or add a float and a color. One of the
important function that every subtype has is to print itself in a
special format. For 'color' it would be :

'type' + 'name' + ' = color('+color[0]+', '+color[2]+',
'+color[2]+');'
Result: color myColor = color(0.5, 0.1, 1.0);

I hope this will make things more clearer. If you do have any
suggestions then please send it across.

Prashant
Jul 18 '08 #6

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

Similar topics

53
by: dterrors | last post by:
Will php 6 do strong typing and/or namespaces? I was shocked to find out today that there are some people who actually argue that weak typing is somehow better. I didn't even know there was a...
12
by: Michael Muller | last post by:
Is there currently any plan to introduce static typing in any future version of Python? (I'm not entirely sure that "static typing" is the right term: what I'm talking about is the declaration of...
0
by: David Mertz, Ph.D. | last post by:
A reader of my book (I dunno if the printed or electronic version), emailed me with a common misunderstanding about typing. I thought other readers might benefit from my note to him too. Not that...
12
by: Jason Tesser | last post by:
I work for at a college where I am one of 2 full-time developers and we are looking to program a new software package fro the campus. This is a huge project as it will include everything from...
94
by: Gabriel Zachmann | last post by:
Is it correct to say that strong/weak typing does not make a difference if one does not use any pointers (or adress-taking operator)? More concretely, I am thinking particularly of Python vs C++....
6
by: Christian Convey | last post by:
Hi guys, I'm looking at developing a somewhat complex system, and I think some static typing will help me keep limit my confusion. I.e.: ...
11
by: Joseph S. | last post by:
Hi all, how do I avoid typing the keyword "$this->" every time I need to reference a member of a class inside the class? (coming from a world of cozy auto-complete enabled Java / .Net IDEs I...
15
by: atbusbook | last post by:
lets say you want a generic numerical algorithom like sum Ruby def sum lst lst.inject(0){|total,current| total*current} end Java // i dont know if there is a numeric super class for numbers
12
by: MartinRinehart | last post by:
I'm writing Python as if it were strongly typed, never recycling a name to hold a type other than the original type. Is this good software engineering practice, or am I missing something...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.