473,761 Members | 2,455 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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().repla ce(" ", "_")
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__(se lf, s.strip().repla ce(" ", "_"))

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 1672
In article <cd**********@n ebula.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().repla ce(" ", "_")
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__(se lf, s.strip().repla ce(" ", "_"))


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().repla ce(" ", "_")
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(newn ame)
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/FxXJd01MZaTXX0R AhBmAJ9fZawKI2G V8a3vnAis7dgk84 Y/ewCfUuHg
pJHyulTFhBC/+HBxuaQxJXA=
=Nquj
-----END PGP SIGNATURE-----

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

class Identifier(str) :
def __init__(self, s = ""):
str.__init__(se lf, s.strip().repla ce(" ", "_"))


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().repla ce(" ", "_"))

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,Id entifier):
raise TypeError, 'name must be of type Identifier!'
self._name = v

name = property(setnam e,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
2192
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 declaration obviously refers to the 'long total' in total.c? Is my compiler wrong? total.c
5
2040
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() only returns public members and I would like to avoid using reflection due to its performance impact. Not sure if using an enumerator would help. The code below illustrates what I want to do. If this is doable, the benefit would be that there...
6
5803
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 the need to have abstract class types in C#? Derived classes from abstract base classes must overrided the abstract method defininition anyway, so why not just provide a complete definition for the abstract method when defining the containing...
4
2720
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); I get "syntax error: identifier" and "undeclared identifier". Since they're in the same namespace, and even in the same project, do I need
18
6523
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 in other assemblies from instantiating them. There is a factory class that instantiates them. Only the factory should do so, because some of these classes have subclasses that will be created instead. The decision of which class to instantiate...
7
12891
by: Tony Tone | last post by:
I am having trouble resolving this issue: Server Error in '/test' Application. -------------------------------------------------------------------------------- Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
4
2486
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 m_Token = null in order to destroy the session token when the user logs out. However, I'm finding that setting class instance to null results in no header being sent back to the client, with the result that the client actually remains with an...
11
6257
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 the app is concerned). The problem is, If someone makes a typo, they may get an unexpected error due accidentally calling the original attribute instead of the wrapped version. Does anyone have a simple solution for this?
6
38062
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,
0
9522
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9336
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
9948
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...
0
9765
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
8770
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5364
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3866
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
3
3446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2738
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.