Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

derived class name in python 2.6/2.7

8 views
Skip to first unread message

Sells, Fred

unread,
Jan 30, 2013, 3:05:52 PM1/30/13
to pytho...@python.org
This is simple, but I just cannot find it after quite a bit of searching

I have this basic design

class A:
def __init__(self):
print 'I am an instance of ', self.__class__.name

class B(A):
pass


X = B
I would like this to print "I am an instance of B" but I keep getting A. Can someone help me out here.

Oscar Benjamin

unread,
Jan 30, 2013, 3:17:05 PM1/30/13
to Sells, Fred, pytho...@python.org
On 30 January 2013 20:05, Sells, Fred <fred....@adventistcare.org> wrote:
> This is simple, but I just cannot find it after quite a bit of searching
>
> I have this basic design
>
> class A:
> def __init__(self):
> print 'I am an instance of ', self.__class__.name

Did you mean to use __name__ instead of name?

>
> class B(A):
> pass
>
> X = B

I assume that this is
X = B()

> I would like this to print "I am an instance of B" but I keep getting A. Can someone help me out here.

If you make those two changes then it should do what you want.


Oscar

Dave Angel

unread,
Jan 30, 2013, 3:20:33 PM1/30/13
to pytho...@python.org
On 01/30/2013 03:05 PM, Sells, Fred wrote:
> This is simple, but I just cannot find it after quite a bit of searching
>
> I have this basic design
>
> class A:
> def __init__(self):
> print 'I am an instance of ', self.__class__.name
>
> class B(A):
> pass
>
>
> X = B
> I would like this to print "I am an instance of B" but I keep getting A. Can someone help me out here.
>

Why would creating an alias for class B execute the initializer for
either class?

perhaps you meant:

x = B()

BTW, since you're on 2.x python, you should derive A from object.
Otherwise it's an old-style class.

--
DaveA
0 new messages