473,396 Members | 1,921 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,396 software developers and data experts.

identifier class enforcement

I work on building a metamodel from an UML diagram (serialized as xmi).
There I have a class called Class that represents a class from the UML
model. The Class has a name member and ininitially it was a string. What I
want to do is to enfoce the class name be an identifier (for example to
exclude white spaces etc.).
I defined an Identifier class, having the builtin str as base class. I have
2 problems:
1. The string is not initialized with the s.strip().replace(" ", "_")
expression.
2. I can at any time change the Class.name member type from client code,
so my enforcement with the Identifier class is gone.

I know Python is very weak typed, but can there is a solution for my second
problem ? Or can I model the problem in some other way ?
class Identifier(str):
def __init__(self, s = ""):
str.__init__(self, s.strip().replace(" ", "_"))

class Class:
def __init__(self, name = ""):
self.name = Identifier(name)
# ....
c = Class(" Circle ")
print type(c.name)
print c.name # will print " Circle " and not "Circle" as I
expected

c.name = "Bubu" # I change the type from Identifier to string
print type(c.name)
print c.name

Thanks,
Florian.
Jul 18 '05 #1
4 1657
In article <cd**********@nebula.dnttm.ro>,
"Florian Preknya" <bo**@coco.ro> wrote:
I work on building a metamodel from an UML diagram (serialized as xmi).
There I have a class called Class that represents a class from the UML
model. The Class has a name member and ininitially it was a string. What I
want to do is to enfoce the class name be an identifier (for example to
exclude white spaces etc.).
I defined an Identifier class, having the builtin str as base class. I have
2 problems:
1. The string is not initialized with the s.strip().replace(" ", "_")
expression.
2. I can at any time change the Class.name member type from client code,
so my enforcement with the Identifier class is gone.

I know Python is very weak typed, but can there is a solution for my second
problem ? Or can I model the problem in some other way ?
class Identifier(str):
def __init__(self, s = ""):
str.__init__(self, s.strip().replace(" ", "_"))


As far as I know, strings are immutable, so you have to set
a str descendant up using `str.__new__`.
Regards. Mel.
Jul 18 '05 #2
I'd write Identifier as a function:
def Identifier(s):
return s.strip().replace(" ", "_")
unless it's important that Identifier be a class. If it is, use a str
subclass and the __new__ method as suggested by another poster.

In Class, I'd use a property to call a setter function when name is
modified:
class Class(object): #subclass of object required for property to work
def set_name(self, newname):
self.__name = Identifier(newname)
def get_name(self):
return self.__name
name = property(get, set)

def __init__(self, name):
self.name = name

The setting of self.name in __init__ or anywhere else in the program
will go through the setter function, set_name, enforcing the requirement
that the name be an Identifier.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFA/FxXJd01MZaTXX0RAhBmAJ9fZawKI2GV8a3vnAis7dgk84Y/ewCfUuHg
pJHyulTFhBC/+HBxuaQxJXA=
=Nquj
-----END PGP SIGNATURE-----

Jul 18 '05 #3
On Mon, 19 Jul 2004, Mel Wilson wrote:
In article <cd**********@nebula.dnttm.ro>,
"Florian Preknya" <bo**@coco.ro> wrote:
1. The string is not initialized with the s.strip().replace(" ", "_")
expression.

class Identifier(str):
def __init__(self, s = ""):
str.__init__(self, s.strip().replace(" ", "_"))


As far as I know, strings are immutable, so you have to set
a str descendant up using `str.__new__`.


I've had to do this before. Using __new__, what you want to do is:

class Identifier(str):
def __new__(cls, s = ""):
return str.__new__(cls, s.strip().replace(" ", "_"))

As Mel pointed out, strings are immutable, so you have to set their value
before they are created (i.e. create them with a value).
2. I can at any time change the Class.name member type from client
code, so my enforcement with the Identifier class is gone.


You can enforce this in Class using properties:

class Class(object): # must be new-style class for this to work
def getname(self):
return self._name

def setname(self,v):
if not isinstance(v,Identifier):
raise TypeError, 'name must be of type Identifier!'
self._name = v

name = property(setname,getname)

Now, any assignment to or retrieval from Class.name will transparently go
through Class.getname() and Class.setname().

However, as mentioned by Jeff, a function Identifier() might be a bit
neater than a class. In this case, you can force name to be of type
Identifier by defining setname() like this:

def setname(self,v):
self._name = Identifier(v)

This will also work if you use the class approach.

Depending on your application, it may be better just to use setname() and
getname() directly, and forgo use of Class.name. Some think this is
better OO methodology all around, while others think properties are
cleaner in certain instances. I'll let you be the judge ;)

Hope this helps.

Jul 18 '05 #4
On Mon, 19 Jul 2004, Christopher T King wrote:
You can enforce this in Class using properties:
Previously, Jeff Epler wrote:
In Class, I'd use a property to call a setter function when name is
modified:


Whoops, didn't see that part of your post, Jeff -- sorry!
That's what I get for using Pine as my newsreader :P

Jul 18 '05 #5

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

Similar topics

7
by: Kobu | last post by:
The code below isn't compiling for me (error message: conflicting types for 'total' - pointing to the extern declaration). Why wouldn't this work, since the types are different, the extern...
5
by: Bob | last post by:
I want to find a way to detect the existance of the private member of a particular type in the derived class from inside the base class itself and call its Dispose() method. Reflection GetFields()...
6
by: Dan Sikorsky | last post by:
If we were to define all abstract methods in an abstract class, thereby making that class non-abstract, and then override the heretofore 'abstract' methods in a derived class, wouldn't that remove...
4
by: Stephen Corey | last post by:
I've got 2 classes in 2 seperate header files, but within the same namespace. If I use a line like: // This code is inside Class2's header file Class1 *newitem = new Class1(param1, param2); ...
18
by: Peter Gummer | last post by:
This is a design question. I have a project containing a dozen or so classes with protected internal constructors. My reason for having protected internal constructors is to prevent classes...
7
by: Tony Tone | last post by:
I am having trouble resolving this issue: Server Error in '/test' Application. -------------------------------------------------------------------------------- Compilation Error Description:...
4
by: Joseph Geretz | last post by:
We use a Soap Header to pass a token class (m_Token) back and forth with authenticated session information. Given the following implementation for our Logout method, I vastly prefer to simply code...
11
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as...
6
by: muby | last post by:
Hi everybody :) I'm modifying a C++ code in VC++ 2005 my code snippet void BandwidthAllocationScheduler::insert( Message* msg, BOOL* QueueIsFull,
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
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...
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
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...
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.