473,396 Members | 1,933 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.

python nested class

greetings....

in a python nested class is it possible to change the value of the
parent class's variable without actually creating an instance of the
parent class, consider this code:

class mother:
x=0
def __init__(self):
self.x=1
def show(self):
print self.x
class child:
def increase(self,num):
# mother.increase=num
o = mother()
o.show()
y=mother.child()
y.increase(20)
# this should print 20
o.show()

...... is it possible somehow ???

thanks and regards,
vedanta
Jul 21 '05 #1
4 4404
Vedanta Barooah wrote:
o = mother()
o.show()
y=mother.child()
y.increase(20)
# this should print 20
o.show()

...... is it possible somehow ???
Hi,

this should do what you want:

--- test.py
class mother:
x=0
def __init__(self):
mother.x=1
def show(self):
print mother.x
class child:
def increase(self,num):
mother.x=num

o = mother()
o.show()
y=mother.child()
y.increase(20)
# this should print 20
o.show()

---pythonw -u "test.py" 1
20Exit code: 0


HtH, Roland
Jul 21 '05 #2
Roland Heiber wrote:
Vedanta Barooah wrote:
o = mother()
o.show()
y=mother.child()
y.increase(20)
# this should print 20
o.show()

...... is it possible somehow ???

Hi,

this should do what you want:

--- test.py
class mother:
x=0
def __init__(self):
mother.x=1
def show(self):
print mother.x
class child:
def increase(self,num):
mother.x=num

o = mother()
o.show()
y=mother.child()
y.increase(20)
# this should print 20
o.show()


---
pythonw -u "test.py"

1
20


This may *not* be what the op want...
#--- test2.py

class mother(object):
x=0
def __init__(self, name):
self.name = name
mother.x=1
def show(self):
print "in %s: %d" % (self.name, mother.x)
class child(object):
def increase(self,num):
mother.x=num

o = mother('o')
o.show()
y=mother.child()
y.increase(20)
# this should print 20
o.show()

o2 = mother('o2')
o2.show()
y2=mother.child()
y2.increase(10)
o2.show()
o.show()
--
bruno desthuilliers
ruby -e "print 'o****@xiludom.gro'.split('@').collect{|p|
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')"
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 21 '05 #3
Vedanta Barooah wrote:
in a python nested class is it possible to change the value of the
parent class's variable without actually creating an instance of the
parent class


Python nested classs are like *static* Java nested classes. Non-static
Java classes are very different in that they have an implicit reference
to an instance of the enclosing class. This is why you can instantiate
non-static inner classes only in the context (= non-static method) of a
specific object. There is no direct equivalent to this in Python, so you
have to do the steps yourself.

- the constructor takes an additional argument, the 'outer' object,
which has to be kept in the object:
def __init__ (self, outer, ...):
self.outer = outer

- when creating the inner object, the outer object must be passed to the
constructor
obj = InnerClass (self)

- the outer object must be explicitely referenced:
self.outer.increase (20)

Daniel
Jul 21 '05 #4
"Daniel Dittmar" <da************@sap.corp> wrote:
Vedanta Barooah wrote:
in a python nested class is it possible to change the value of the
parent class's variable without actually creating an instance of the
parent class


Python nested classs are like *static* Java nested classes. Non-static
Java classes are very different in that they have an implicit reference
to an instance of the enclosing class. This is why you can instantiate
non-static inner classes only in the context (= non-static method) of a
specific object. There is no direct equivalent to this in Python, so you
have to do the steps yourself.

- the constructor takes an additional argument, the 'outer' object,
which has to be kept in the object:
def __init__ (self, outer, ...):
self.outer = outer

- when creating the inner object, the outer object must be passed to the
constructor
obj = InnerClass (self)

- the outer object must be explicitely referenced:
self.outer.increase (20)

Daniel


Or you can automate these steps and make implicit the reference to the
outer object using a descriptor:

#====== Test =============================================

def test():
class Outer:
def __init__(self,x): self.x = x

# if python gets class decorators someday,
# an inner class could be specified simply by:
#@innerclass
class Inner:
def __init__(self, y): self.y = y
def sum(self): return self.x + self.y
# as of python 2.4
Inner = innerclass(Inner)

outer = Outer(1)
inner = outer.Inner(2)
assert inner.sum() == 3
# outer.x, inner.x, inner.__outer__.x refer to the same object
outer.x = 4; assert inner.sum() == 6
inner.x = 10; assert inner.sum() == 12
inner.__outer__.x = -1; assert inner.sum() == 1
# an inner class must be bounded to an outer class instance
try: Outer.Inner(0)
except AttributeError, e: pass #print e
else: assert False

#================================================= ======

def innerclass(cls):
'''Class decorator for making a class behave as a Java (non-static)
inner class.

Each instance of the decorated class is associated with an instance
of its enclosing class. The outer instance is referenced implicitly
when an attribute lookup fails in the inner object's namespace. It
can also be referenced explicitly through the property '__outer__'
of the inner instance.
'''
if hasattr(cls, '__outer__'):
raise TypeError('Existing attribute "__outer__" '
'in inner class')
class InnerDescriptor(object):
def __get__(self, outer, outercls):
if outer is None:
raise AttributeError('An enclosing instance that '
'contains %s.%s is required' %
(cls.__name__, cls.__name__))
clsdict = cls.__dict__.copy()
# explicit read-only reference to the outer instance
clsdict['__outer__'] = property(lambda s: outer)
# implicit lookup in the outer instance
clsdict['__getattr__'] = lambda s,attr: getattr(outer,attr)
def __setattr__(this, attr, value):
# setting an attribute in the inner instance sets the
# respective outer instance if and only if the
# attribute is already defined in the outer instance
if hasattr(outer, attr): setattr(outer,attr,value)
else: super(this.__class__,this).__setattr__(attr,
value)
clsdict['__setattr__'] = __setattr__
return type(cls.__name__, cls.__bases__, clsdict)
return InnerDescriptor()
Regards,
George

Jul 21 '05 #5

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

Similar topics

49
by: Ville Vainio | last post by:
I don't know if you have seen this before, but here goes: http://text.userlinux.com/white_paper.html There is a jab at Python, though, mentioning that Ruby is more "refined". -- Ville...
6
by: Timothy Fitz | last post by:
While I agree that the Zen of Python is an amazingly concise list of truisms, I do not see any meaning in: Flat is better than nested. I strive for balance between flat and nested. Does anyone...
10
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. ...
14
by: Michele Simionato | last post by:
I would like to know what is available for scripting browsers from Python. For instance, webbrowser.open let me to perform GET requests, but I would like to do POST requests too. I don't want to...
14
by: Mark Dufour | last post by:
After nine months of hard work, I am proud to introduce my baby to the world: an experimental Python-to-C++ compiler. It can convert many Python programs into optimized C++ code, without any user...
0
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 417 open ( -6) / 3565 closed (+12) / 3982 total ( +6) Bugs : 960 open ( -3) / 6498 closed (+19) / 7458 total (+16) RFE : 266 open...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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:
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
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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,...

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.