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

Class Inheritance - What am I doing wrong?

My example:

class A(object):

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

def getName(self):
return self.__name

class B(A):

def __init__(self,name=None):
super(A,self).__init__()

def setName(self, name):
self.__name = name

if __name__ == '__main__':

a = A('class a')
print a.getName()

b = B('class b')
print b.getName()

b.setName('class b, reset')
print b.getName()

I get the following error:

mtinky:~ brian$ python teste.py
class a
Traceback (most recent call last):
File "teste.py", line 23, in <module>
print b.getName()
File "teste.py", line 7, in getName
return self.__name
AttributeError: 'B' object has no attribute '_A__name'

Am I *not* using super() correctly? Also, did I define my the class B
constructor correctly?
Jun 27 '08 #1
8 1135
On Apr 24, 10:22*pm, Brian Munroe <brian.e.mun...@gmail.comwrote:
My example:

class A(object):

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

* * * * def getName(self):
* * * * * * * * return self.__name

class B(A):

* * * * def __init__(self,name=None):
* * * * * * * * super(A,self).__init__()

* * * * def setName(self, name):
* * * * * * * * self.__name = name

if __name__ == '__main__':

* * * * a = A('class a')
* * * * print a.getName()

* * * * b = B('class b')
* * * * print b.getName()

* * * * b.setName('class b, reset')
* * * * print b.getName()

I get the following error:

mtinky:~ brian$ python teste.py
class a
Traceback (most recent call last):
* File "teste.py", line 23, in <module>
* * print b.getName()
* File "teste.py", line 7, in getName
* * return self.__name
AttributeError: 'B' object has no attribute '_A__name'

Am I *not* using super() correctly? *Also, did I define my the class B
constructor correctly?
Exactly, you used it wrong. It's super(B, self).

But before you start using super() everywhere, read this:

http://fuhm.net/super-harmful/

I love Python, but super() is one of those tricky things...
Jun 27 '08 #2
Brian Munroe <br************@gmail.comwrites:
My example:

class A(object):

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

def getName(self):
return self.__name

class B(A):

def __init__(self,name=None):
super(A,self).__init__()

def setName(self, name):
self.__name = name

if __name__ == '__main__':

a = A('class a')
print a.getName()

b = B('class b')
print b.getName()

b.setName('class b, reset')
print b.getName()

I get the following error:

mtinky:~ brian$ python teste.py
class a
Traceback (most recent call last):
File "teste.py", line 23, in <module>
print b.getName()
File "teste.py", line 7, in getName
return self.__name
AttributeError: 'B' object has no attribute '_A__name'

Am I *not* using super() correctly? Also, did I define my the class B
constructor correctly?
You have fallen victim to the Name Mangling Trap [1]. Replace the
leading double underscore in the __name attribute with a single one,
and Python shall calm down and let your code behave as you expect it
to.

That is, if you also pass the name parameter to super(A,self).__init__
in B's __init__ method

[1] http://docs.python.org/ref/atom-identifiers.html

--
Arnaud
Jun 27 '08 #3
Arnaud Delobelle <ar*****@googlemail.comwrites:
That is, if you also pass the name parameter to super(A,self).__init__
in B's __init__ method
Oops. should be super(B, self).__init__(name), of course.

--
Arnaud
Jun 27 '08 #4
Brian Munroe wrote:
My example:

class A(object):

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

def getName(self):
return self.__name

class B(A):

def __init__(self,name=None):
super(A,self).__init__()

def setName(self, name):
self.__name = name

if __name__ == '__main__':

a = A('class a')
print a.getName()

b = B('class b')
print b.getName()

b.setName('class b, reset')
print b.getName()

I get the following error:

mtinky:~ brian$ python teste.py
class a
Traceback (most recent call last):
File "teste.py", line 23, in <module>
print b.getName()
File "teste.py", line 7, in getName
return self.__name
AttributeError: 'B' object has no attribute '_A__name'

Am I *not* using super() correctly? Also, did I define my the class B
constructor correctly?
--
http://mail.python.org/mailman/listinfo/python-list
Tell us what you are trying to do and what you expected to happen.

If you are trying to do simple inheritance, you don't need the supers,
and you should not invoke the name mangling implied by the double
underscore.

If you *are* trying to use the name mangling, then you still don't need
the super.
Gary Herron
Jun 27 '08 #5
Ok, so thanks everyone for the helpful hints. That *was* a typo on my
part (should've been super(B...) not super(A..), but I digress)

I'm building a public API. Along with the API I have a few custom
types that I'm expecting API users to extend, if they need too. If I
don't use name mangling, isn't that considered bad practice (read not
defensive programming) to not protect those 'private' fields?
Jun 27 '08 #6
Brian Munroe <br************@gmail.comwrites:
Ok, so thanks everyone for the helpful hints. That *was* a typo on my
part (should've been super(B...) not super(A..), but I digress)

I'm building a public API. Along with the API I have a few custom
types that I'm expecting API users to extend, if they need too. If I
don't use name mangling, isn't that considered bad practice (read not
defensive programming) to not protect those 'private' fields?
The problem is that you are using name mangling for an attribute which
is accessed by several generations of a class hierarchy. Name
mangling is only useful for attributes you *don't* want to share with
subclasses (or bases).

In python, use attributes starting with a single underscore (such as
_name). It tells users that they shouldn't mess with them. By
design, python doesn't include mechanisms equivalent to the Java / C++
'private'.

--
Arnaud
Jun 27 '08 #7
Brian Munroe a écrit :
Ok, so thanks everyone for the helpful hints. That *was* a typo on my
part (should've been super(B...) not super(A..), but I digress)

I'm building a public API. Along with the API I have a few custom
types that I'm expecting API users to extend, if they need too. If I
don't use name mangling, isn't that considered bad practice (read not
defensive programming) to not protect those 'private' fields?
There would be a lot to say about whether defensive programming is a
good practice or not. At least in the context of hi-level languages with
exception handling and automatic memory management.

Anyway:
- there's just no way to make anything truly "private" in Python
- the convention is that attributes (including methods - they are
attributes too) whose name starts with a single leading underscore are
implementation stuff and should not be messed with. IOW, the contract is
"mess with them and you're on your own".
- name mangling is only useful when you really need to make sure an
implementation attribute won't be *accidentally* shadowed. These
attributes should only be used by methods that are not themselves
supposed to be overridden or extended by user code. FWIW, I must have
used them less than half a dozen times in 7+ years (and I wrote more
than a couple mini-frameworks, with lot of black-juju metaclasses and
custom descriptors magic in them).

So just use single-leading-underscore for implementation attributes, and
document what the users are supposed to extend and what they're supposed
to leave alone.

My 2 cents.
Jun 27 '08 #8
On Apr 24, 10:11 pm, Arnaud Delobelle <arno...@googlemail.comwrote:
In python, use attributes starting with a single underscore (such as
_name). It tells users that they shouldn't mess with them. By
design, python doesn't include mechanisms equivalent to the Java / C++
'private'.
Arnaud, Gabriel:

Ok, Ok, I'll trust my users to not abuse my API :) I didn't realize
that 'private' meant 'private, even to sub-classes' - it is all
becoming clear to me now!

Thanks for the help, and I'm going to re-read 'Python is Not Java'
right about now (I've spent the past few months knee-deep in Java, I
guess I need to cleanse myself)
Jun 27 '08 #9

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

Similar topics

5
by: Bruce Lee Roy | last post by:
Hi, I am using visual studio.net and I am having problems using this bit of code when I create an instance, //////////////////////////////////////////// template<class T> class matrix : public...
4
by: Robby White | last post by:
How can access properties of an object lower down in the hierarchy of my class structure? For example; Company.Customers(0).Products(0).ShowCompanyName In the above Show method I want to...
9
by: mead | last post by:
What kind of classes is qualified as "concrete classes"? When should a member function in a class defined as "pure virtual" and when as "virtual"? Thanks!
9
by: Banaticus Bart | last post by:
I wrote an abstract base class from which I've derived a few other classes. I'd like to create a base class array where each element is an instance of a derived object. I can create a base class...
13
by: Walt Karas | last post by:
The following gives an error in the declaration of the member function x() of the class template Tpl, compiliing with a recent version of GCC under Solaris: class A { }; class B { }; ...
7
by: WXS | last post by:
Vote for this idea if you like it here: http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=5fee280d-085e-4fe2-af35-254fbbe96ee9...
9
by: Rudy | last post by:
Hello All! I'm a little confused on Public Class or Modules. Say I have a this on form "A" Public Sub Subtract() Dim Invoice As Decimal Dim Wage As Decimal Static PO As Decimal Invoice =...
21
by: Daz | last post by:
Hi everyone. I am trying to create an extension of the mysqli class within PHP, and I am finding it quite difficult. I am fairly new to PHP classes, and decided to give them a go. Here's what I...
4
by: Alan Mailer | last post by:
Again, I'm new to VB.net and there is something I need help with: Like (I assume) many of us, over time I want to be able to create some VB.net classes that I might want to use in more than one...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...

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.