473,651 Members | 3,068 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about classes and possible closure.

This is all an intro learning experience for me, so please feel free to
explain why what I'm trying to do is not a good idea.

In the Cookbook, they have a recipe for how to create global constants.

-----------------
class _const:
class ConstError(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_key(name):
raise self.ConstError , "Can't rebind const(%s)"%name
self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()
----------------

I'd like to be able to create constants within a class. (Yes I understand
that uppercase names is a far better and easier convention but this is a
learning experience for me.)

I can't get this to work, but my idea is that MyClass is defined thusly:

class ConstError(Type Error): pass
class Myclass:
def mprint(self):
print "C1 = ", self._C1

# Define a subclass to create constants. It refs upself to access
# the uplevel copy of self.
class _const:
class ConstError(Type Error): pass
def __setattr__(_up self,name,value ):
if upself.__dict__ .has_key(name):
raise self.ConstError , "Can't rebind const(%s)"%name
else:
print "Just set something"
upself.__dict__[name]=value

# I want the const instance to be contained in this class so I
# instantiate here in the constructor.
def __init__(self):
upself = self
upself.consts = const()
upself.consts._ C1 = 0
setattr(upself. consts, "_C1", 44)
self = upself

Then the call in another file is this:
#! /usr/bin/python
from c2 import Myclass
foo = Myclass()
foo.mprint()
# end

Is it possible to nest a class in another class and is it possible to make
this work?

TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Feb 21 '07 #1
3 1254
On Feb 21, 4:30 pm, "Steven W. Orr" <ste...@syslang .netwrote:
This is all an intro learning experience for me, so please feel free to
explain why what I'm trying to do is not a good idea.

In the Cookbook, they have a recipe for how to create global constants.

-----------------
class _const:
class ConstError(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_key(name):
raise self.ConstError , "Can't rebind const(%s)"%name
self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()
----------------

I'd like to be able to create constants within a class. (Yes I understand
that uppercase names is a far better and easier convention but this is a
learning experience for me.)

I can't get this to work, but my idea is that MyClass is defined thusly:

class ConstError(Type Error): pass
class Myclass:
def mprint(self):
print "C1 = ", self._C1
Looking ahead, this should be "self.consts._C 1", not "self._Cl".
# Define a subclass to create constants. It refs upself to access
# the uplevel copy of self.
It's better to stick with the conventions. But regardless, you have to
be consistent, as we see in a moment.
class _const:
class ConstError(Type Error): pass
This is redundant. Even though this ConstError and the one defined
before the Myclass definition are in completely different scopes, so
there's no conflict, I doubt this is what you meant to do.
def __setattr__(_up self,name,value ):
Notice your first argument here is "_upself", with an underscore.
if upself.__dict__ .has_key(name):
Now you're using "upself", without an underscore, which is undefined.
raise self.ConstError , "Can't rebind const(%s)"%name
Now you're using "self", which is also undefined.
else:
print "Just set something"
upself.__dict__[name]=value
Once again, "upself" instead of "_upself".

Just follow the convention: always use "self".
>
# I want the const instance to be contained in this class so I
# instantiate here in the constructor.
def __init__(self):
upself = self
Why "upself = self"? You could just as easily use "self". Follow the
conventions.
upself.consts = const()
I'm guessing this is your error? That should be "upself.con sts =
self._const()"
upself.consts._ C1 = 0
setattr(upself. consts, "_C1", 44)
Obviously, this is going to raise an error, because you're redefining
_Cl.
self = upself
Again, why the weird juggling between self and upself? First of all,
self and upself are references to the same object right now, so "self
= upself" has no after-effect at all. Second of all, even if it did,
all it would be doing is reassigning the local variable "self" to a
different object; it has no effect on the object you're working with.
Then the call in another file is this:
#! /usr/bin/python
from c2 import Myclass
foo = Myclass()
foo.mprint()
# end

Is it possible to nest a class in another class and is it possible to make
this work?
Yes, it is possible to nest a class in another class. Yes, it is
possible to make this work. However, it is good practice to post your
error message along with your code, so we don't have to guess.

Here's an untested rewrite of your code:

class Myclass:
def mprint(self):
print "C1 = ", self.consts._C1

# Define a subclass to create constants. It refs upself to access
# the uplevel copy of self.
class _const:
class ConstError(Type Error): pass
def __setattr__(_up self,name,value ):
if _upself.__dict_ _.has_key(name) :
raise _upself.ConstEr ror, "Can't rebind
const(%s)"%name
else:
print "Just set something"
_upself.__dict_ _[name]=value

# I want the const instance to be contained in this class so I
# instantiate here in the constructor.
def __init__(self):
self.consts = const()
self.consts._C1 = 0
# This will raise an error!!!!
setattr(self.co nsts, "_C1", 44)
TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Feb 21 '07 #2
Steven W. Orr wrote:
This is all an intro learning experience for me, so please feel free to
explain why what I'm trying to do is not a good idea.

In the Cookbook, they have a recipe for how to create global constants.

-----------------
class _const:
class ConstError(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_key(name):
raise self.ConstError , "Can't rebind const(%s)"%name
self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()
----------------

I'd like to be able to create constants within a class. (Yes I
understand that uppercase names is a far better and easier convention
but this is a learning experience for me.)

I can't get this to work, but my idea is that MyClass is defined thusly:

class ConstError(Type Error): pass
class Myclass:
def mprint(self):
print "C1 = ", self._C1

# Define a subclass to create constants. It refs upself to access
# the uplevel copy of self.
class _const:
class ConstError(Type Error): pass
def __setattr__(_up self,name,value ):
if upself.__dict__ .has_key(name):
raise self.ConstError , "Can't rebind const(%s)"%name
else:
print "Just set something"
upself.__dict__[name]=value

# I want the const instance to be contained in this class so I
# instantiate here in the constructor.
def __init__(self):
upself = self
upself.consts = const()
upself.consts._ C1 = 0
setattr(upself. consts, "_C1", 44)
self = upself

Then the call in another file is this:
#! /usr/bin/python
from c2 import Myclass
foo = Myclass()
foo.mprint()
# end

Is it possible to nest a class in another class and is it possible to
make this work?

TIA

I see no reason to nest classes, ever, as each creates a seperate name
space. Better would be to de-nest _const and make it available to all of
your classes, otherwise you have lost some of its reusability. A class
is esentially the definition of a behavior and so nesting assumes that
the nesting confers upon the outer class that having a nested class
changes its behavior. This is what composition is for. If you want a
reference to a class in your code, then make an assignment:
# Const.py
class ConstError(Type Error): pass

class Const:
def __setattr__(sel f, name, value):
if hasattr(self, name):
raise ConstError, "Can't rebind const(%s)" % name
else:
print "Just set something"
self.__dict__[name] = value
# Myclass.py
import Const

class Myclass:

def mprint(self):
print "C1 = ", self.consts._C1

def __init__(self):
self.consts = Const()
self.consts._C1 = 0
# This will raise an error!!!!
self.consts._C1 = 44
This makes a lot more sense and follows the "flat is better than nested"
rule. Notice how, otherwise, ConstError would be triple nested. Now
you can import Const and have constants in all your classes.

I also pythonized some of your code.

James
Feb 22 '07 #3
James Stroud wrote:
Steven W. Orr wrote:
>This is all an intro learning experience for me, so please feel free
to explain why what I'm trying to do is not a good idea.

In the Cookbook, they have a recipe for how to create global constants.

-----------------
class _const:
class ConstError(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_key(name):
raise self.ConstError , "Can't rebind const(%s)"%name
self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()
----------------

I'd like to be able to create constants within a class. (Yes I
understand that uppercase names is a far better and easier convention
but this is a learning experience for me.)

I can't get this to work, but my idea is that MyClass is defined thusly:

class ConstError(Type Error): pass
class Myclass:
def mprint(self):
print "C1 = ", self._C1

# Define a subclass to create constants. It refs upself to access
# the uplevel copy of self.
class _const:
class ConstError(Type Error): pass
def __setattr__(_up self,name,value ):
if upself.__dict__ .has_key(name):
raise self.ConstError , "Can't rebind const(%s)"%name
else:
print "Just set something"
upself.__dict__[name]=value

# I want the const instance to be contained in this class so I
# instantiate here in the constructor.
def __init__(self):
upself = self
upself.consts = const()
upself.consts._ C1 = 0
setattr(upself. consts, "_C1", 44)
self = upself

Then the call in another file is this:
#! /usr/bin/python
from c2 import Myclass
foo = Myclass()
foo.mprint()
# end

Is it possible to nest a class in another class and is it possible to
make this work?

TIA


I see no reason to nest classes, ever, as each creates a seperate name
space. Better would be to de-nest _const and make it available to all of
your classes, otherwise you have lost some of its reusability. A class
is esentially the definition of a behavior and so nesting assumes that
the nesting confers upon the outer class that having a nested class
changes its behavior. This is what composition is for. If you want a
reference to a class in your code, then make an assignment:
# Const.py
class ConstError(Type Error): pass

class Const:
def __setattr__(sel f, name, value):
if hasattr(self, name):
raise ConstError, "Can't rebind const(%s)" % name
else:
print "Just set something"
self.__dict__[name] = value
# Myclass.py
import Const

class Myclass:

def mprint(self):
print "C1 = ", self.consts._C1

def __init__(self):
self.consts = Const()
self.consts._C1 = 0
# This will raise an error!!!!
self.consts._C1 = 44
This makes a lot more sense and follows the "flat is better than nested"
rule. Notice how, otherwise, ConstError would be triple nested. Now you
can import Const and have constants in all your classes.

I also pythonized some of your code.

James
should be self.consts = Const.Const()

James
Feb 22 '07 #4

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

Similar topics

27
2103
by: Ted Lilley | last post by:
What I want to do is pre-load functions with arguments by iterating through a list like so: >>>class myclass: .... pass >>>def func(self, arg): .... print arg >>>mylist = >>>for item in mylist: .... setattr(myclass, item, lamdba self: func(self, item))
20
3103
by: svend | last post by:
I'm messing with some code here... Lets say I have this array: a1 = ; And I apply slice(0) on it, to create a copy: a2 = a1.slice(0); But this isn't a true copy. If I go a1 = 42, and then alert(a2) I will see 42 there too. I'm doubting, but I was
7
337
by: cwhite | last post by:
The answer to this is probably very simple, but it has been a while since I have had to use access. I have two different queries, one counts records: SELECT Closure.Closed_As, Count(Closure.Closed_As) AS Closed_As_Count FROM Closure GROUP BY Closure.Closed_As; and returns something like:
3
3563
by: Sam Kong | last post by:
Hi group, I want to have some advice about immutable objects. I made a constructor. function Point(x, y) { this.x = x; this.y = y; }
7
1860
by: Csaba Gabor | last post by:
I feel like it's the twilight zone here as several seemingly trivial questions are bugging me. The first of the following three lines is a syntax error, while the last one is the only one that shows the alert. What is the essential reason? function () { alert('hi mom'); }(); function () { alert('hi dad'); }(8); var x=function () { alert('hi bro'); }();
4
1471
by: emailscotta | last post by:
Below are some over simplified examples of code the create a single instance of an object and I was hoping some one could give me the pros and cons of each approach. First declaration: In this case a single object is created using object literal notation and both the get and __Private methods are availabile for use and no closure is created. ABC.Util.SomeObject = {
26
2527
by: Cliff Williams | last post by:
Can someone explain the pros/cons of these different ways of creating a class? // 1 function myclass() { this.foo1 = function() {...} } // 2a
11
3019
by: Huayang Xia | last post by:
What will the following piece of code print? (10 or 15) def testClosure(maxIndex) : def closureTest(): return maxIndex maxIndex += 5 return closureTest()
18
1895
by: Tom Cole | last post by:
I'm working on a small Ajax request library to simplify some tasks that I will be taking on shortly. For the most part everything works fine, however I seem to have some issues when running two requests at the same time. The first one stops execution as the second continues. If I place either an alert between the two requests or run the second through a setTimeout of only 1 millisecond, they both work. You can see a working example here:...
0
8361
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
8278
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
8807
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7299
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...
1
6158
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5615
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4290
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1912
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.