Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #54038 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2013-09-12 08:45 +0200 |
| Last post | 2013-09-12 08:45 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Accessing class attribute Peter Otten <__peter__@web.de> - 2013-09-12 08:45 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2013-09-12 08:45 +0200 |
| Subject | Re: Accessing class attribute |
| Message-ID | <mailman.299.1378968339.5461.python-list@python.org> |
chandan kumar wrote:
> Hi ,
>
> I'm new to python ,please correct me if there is any thing wrong with the
> way accessing class attributes.
>
> Please see the below code .I have inherited confid in ExpectId class,
> changed self.print_msg to Hello. Now inherited confid in TestprintmsgID
> class.Now I wanted to print self.print_msg value (which is changed under
> ExpectId class) as Hello under TestprintmsgID. I end up with error saying
> TestprintmsgID has no attribute self.print_msg. Atleast i expect the null
> to be printed.
>
>
>
> class confid():
> def __init__(self):
> self.print_msg = ""
>
> class ExpectId(confid):
>
> def __init__(self):
> self.print_msg = " Hello"
>
> def expectmethod(self):
> print "self.print_mesg = ",self.print_msg
>
> class TestprintmsgID(confid):
>
> def __init__(self):
> "Created Instance"
>
> def printmsgmethod(self):
> print "printmsgmethod print_msg val = ",self.print_msg---- Here is
> the Attribute error
If the class has an __init__() method the initializer of the base class is
not invoked automatically.
In the above code the initializer of TestprintmsgId does nothing, so you can
avoid it. ExpectId.__init__() however must invoke confid.__init_().
The complete example:
class confid():
def __init__(self):
self.print_msg = ""
class ExpectId(confid):
def __init__(self):
confid.__init__(self)
self.print_msg = " Hello"
def expectmethod(self):
print "self.print_mesg = ",self.print_msg
class TestprintmsgID(confid):
def printmsgmethod(self):
print "printmsgmethod print_msg val = ",self.print_msg
Note that there is an alternative way to invoke a baseclass method using
super() which works only for "newstyle classes", i. e. classes that inherit
from object:
class confid(object):
def __init__(self):
self.print_msg = ""
class ExpectId(confid):
def __init__(self):
super(ExpectId, self).__init__()
self.print_msg = " Hello"
def expectmethod(self):
print "self.print_mesg = ",self.print_msg
class TestprintmsgID(confid):
def printmsgmethod(self):
print "printmsgmethod print_msg val = ",self.print_msg
Back to top | Article view | comp.lang.python
csiph-web