473,563 Members | 2,668 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting a class name

Hi,

How does one get the name of a class from within the class code? I
tried something like this as a guess:

self.__name__

Obviously it didn't work.

Anyone know how to do that?

Thanks,

Harlin

Feb 17 '07 #1
14 2788
Harlin Seritt wrote:
Hi,

How does one get the name of a class from within the class code? I
tried something like this as a guess:

self.__name__
Get the class first, then inspect its name:
>>class Foo(object): pass
....
>>f = Foo()
f.__class__._ _name__
'Foo'
>>>
HTH
--
d.
Feb 17 '07 #2
I suppose that you wont get class name into its code (or before
definition end) but not into a method definition.
import sys

def getCodeName(dea p=0):
return sys._getframe(d eap+1).f_code.c o_name
class MyClass (object):
name = getCodeName() + '!'
Feb 18 '07 #3
En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf <Ro**********@g mail.com>
escribió:
I suppose that you wont get class name into its code (or before
definition end) but not into a method definition.
import sys

def getCodeName(dea p=0):
return sys._getframe(d eap+1).f_code.c o_name
class MyClass (object):
name = getCodeName() + '!'
What's the advantage over MyClass.__name_ _?

--
Gabriel Genellina

Feb 18 '07 #4
On Feb 17, 8:33 pm, deelan <g...@zzz.itwro te:
Harlin Seritt wrote:
Hi,
How does one get the name of a class from within the class code? I
tried something like this as a guess:
self.__name__

Get the class first, then inspect its name:
>>class Foo(object): pass
...
>>f = Foo()
>>f.__class__._ _name__
'Foo'
>>>

Why is the __name__ attribute not available to the instance? Why don't
normal lookup rules apply (meaning that a magic attribute will be
looked up on the class for instances) ?

Fuzzyman
http://www.voidspace.org.uk/python/articles.shtml

HTH

--
d.

Feb 18 '07 #5
On 18 Feb 2007 04:24:47 -0800, "Fuzzyman" <fu******@gmail .comwrote:
>On Feb 17, 8:33 pm, deelan <g...@zzz.itwro te:
>Harlin Seritt wrote:
Hi,
How does one get the name of a class from within the class code? I
tried something like this as a guess:
self.__name__

Get the class first, then inspect its name:
> >>class Foo(object): pass
...
> >>f = Foo()
f.__class__._ _name__
'Foo'
> >>>


Why is the __name__ attribute not available to the instance? Why don't
normal lookup rules apply (meaning that a magic attribute will be
looked up on the class for instances) ?
Good question!
>>f = Foo()
dir(f)
['__class__', '__delattr__', '__dict__', '__doc__',
'__getattribute __', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__' , '__repr__', '__setattr__', '__str__',
'__weakref__']
>>dir(f.__class __)
['__class__', '__delattr__', '__dict__', '__doc__',
'__getattribute __', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__' , '__repr__', '__setattr__', '__str__',
'__weakref__']
>>>
Where is '__name__' ?
Dan
Feb 18 '07 #6
On Feb 18, 1:24 pm, "Fuzzyman" <fuzzy...@gmail .comwrote:
Why is the __name__ attribute not available to the instance? Why don't
normal lookup rules apply (meaning that a magic attribute will be
looked up on the class for instances) ?
Because __name__ isn't really an attribute, it is a descriptor defined
on
the metaclass:
>>type(type.__d ict__['__name__'])
<type 'getset_descrip tor'>

See http://users.rcn.com/python/download/Descriptor.htm for a guide to
descriptors, and the papers by me and David Mertz for a guide to
metaclasses.

Michele Simionato

Feb 18 '07 #7
On Feb 18, 1:22 pm, "Michele Simionato" <michele.simion ...@gmail.com>
wrote:
On Feb 18, 1:24 pm, "Fuzzyman" <fuzzy...@gmail .comwrote:
Why is the __name__ attribute not available to the instance? Why don't
normal lookup rules apply (meaning that a magic attribute will be
looked up on the class for instances) ?

Because __name__ isn't really an attribute, it is a descriptor defined
on
the metaclass:
>type(type.__di ct__['__name__'])

<type 'getset_descrip tor'>

Seehttp://users.rcn.com/python/download/Descriptor.htmf or a guide to
descriptors, and the papers by me and David Mertz for a guide to
metaclasses.
Thanks, I'll do some more reading.

I got as far as this on my own:

My guess is that it is because magic attributes are looked up on the
class. When you ask the *class* what its name is, the metaclass
answers on its behalf.

The class has no real ``__name__`` attribute, so when you ask the
instance (which doesn't inherit from the metaclass) you get an
``AttributeErro r``. Is this right ? In which case, how does the
metaclass (typically ``type`` which has many instance) know which
answer to supply ?

A simple test indicates that the name *is* looked up on the
metaclass :

... raw:: html

{+coloring}
>>class meta(type):
... __name__ = 'fish'
...
>>class Test(object):
... __metaclass__ = meta
...
>>Test.__name __
'fish'
{-coloring}

So maybe ``__name__`` is a propery and ``type`` keeps a dictionary of
instances to names, registered in ``type.__new__` ` ?

Fuzzyman
http://www.voidspace.org.uk/python/articles.shtml
Michele Simionato

Feb 18 '07 #8
On Feb 18, 9:17 am, "Gabriel Genellina" <gagsl...@yahoo .com.arwrote:
En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf <Robert.Ka...@g mail.com>
escribió:
I suppose that you wont get class name into its code (or before
definition end) but not into a method definition.
import sys
def getCodeName(dea p=0):
return sys._getframe(d eap+1).f_code.c o_name
class MyClass (object):
name = getCodeName() + '!'

What's the advantage over MyClass.__name_ _?

--
Gabriel Genellina
>>class C(object):
.... name = C.__name__
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in C
NameError: name 'C' is not defined
>>>
Feb 18 '07 #9
En Sun, 18 Feb 2007 14:14:41 -0300, goodwolf <Ro**********@g mail.com>
escribió:
On Feb 18, 9:17 am, "Gabriel Genellina" <gagsl...@yahoo .com.arwrote:
>En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf <Robert.Ka...@g mail.com>
escribió:
I suppose that you wont get class name into its code (or before
definition end) but not into a method definition.
import sys
def getCodeName(dea p=0):
return sys._getframe(d eap+1).f_code.c o_name
class MyClass (object):
name = getCodeName() + '!'

What's the advantage over MyClass.__name_ _?

--
Gabriel Genellina
>>>class C(object):
... name = C.__name__
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in C
NameError: name 'C' is not defined
>>>>
I were asking, why do you want a "name" attribute since "__name__" already
exists and has the needed information. And worst, using an internal
implementation function to do such task.

--
Gabriel Genellina

Feb 18 '07 #10

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

Similar topics

2
6900
by: Eyal | last post by:
Hey, I would appriciate if anyone can help on this one: I have a java object/inteface having a method with a boolean parameter. As I'm trying to call this method from a javascript it fails on a type mismatch. It is positively because of the boolean(java primitive)parameter. It goes fine if I change this parameter to int or String. This...
8
1403
by: abbylee26 | last post by:
User enters account number if another account number is needed User clicks add account which creates another row When validating when they hit submit I want to check to make sure they tell us how much money to charge to all account numbers except the first one (all remaining money goes on the first account number) within the header...
12
2004
by: Sunny | last post by:
Hi All, I have a serious issue regarding classes scope and visibility. In my application, i have a class name "TextFile", and also a few other classes like "TotalWords", "TotalLines" and etc.., which are suppose to describe the structure of my main TextFile class. Also i have created some custom collection classes, which only take items of...
0
3700
by: ruju00 | last post by:
I am getting an error in Login() method of the following class FtpConnection public class FtpConnection { public class FtpException : Exception { public FtpException(string message) : base(message){} public FtpException(string message, Exception innerException) : base(message,innerException){}
20
27741
by: Shawnk | last post by:
I would like to get the class INSTANCE name (not type name) of an 'object'. I can get the object (l_obj_ref.GetType()) and then get the (l_obj_typ.Name) for the class name. I there any way of getting 'l_Fred_my_ins' out of the following. .... My_cls l_Fred_my_ins = new My_cls();
2
2701
cassbiz
by: cassbiz | last post by:
I am using strtotime and I have read up on some examples and am getting the wrong output, it jumps by several days instead of one day at a time. Ultimately what I am trying to accomplish is to set up an arrival time and a departure time for the script. This is using AJAX (which I am such a newbee @) from my earlier post...
1
3177
by: simbarashe | last post by:
Hie could someone please help me with getting and using the current page url. I have a function that gets the url, I want to use it with header(location : XXX) but it wont work. The code is as follows: The code below is for the first page:session_start is in line 3 <link href="css/jobSheet.css" rel="stylesheet" type="text/css" /> ...
0
2902
by: buntyindia | last post by:
Hi, I have a very strange problem with my application. I have developed it using Struts. I have a TextBox With Some fixed value in it and on Submit iam passing it to another page. <html:form action="/login"> <html:text property="userName" value="Bunty"/> <html:submit/>
2
6644
by: karinmorena | last post by:
I'm having 4 errors, I'm very new at this and I would appreciate your input. The error I get is: Week5MortgageGUI.java:151:cannot find symbol symbol: method allInterest(double,double,double) Location: class Week5MortgageGUI Week5MortgageLogic allint = logic.allInterest(amount, term, rate); Week5MortgageGUI.java:152:cannot find symbol...
5
1624
by: tshad | last post by:
I have the following class in my VS 2008 project that has a namespace of MyFunctions. ********************************* Imports System Imports System.Text.RegularExpressions Namespace MyFunctions Public Class BitHandling
0
7659
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...
0
7580
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...
0
7882
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. ...
0
8103
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6244
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...
1
5481
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...
0
5208
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...
1
2079
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1194
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.