How do I get the string with name of a class?

What method do I call to get the name of a class?


Asked by: Andrew657 | Posted: 27-01-2022






Answer 1

In [1]: class Test:
   ...:     pass
   ...: 

In [2]: Test.__name__
Out[2]: 'Test'

Answered by: Ryan969 | Posted: 28-02-2022



Answer 2

It's not a method, it's a field. The field is called __name__. class.__name__ will give the name of the class as a string. object.__class__.__name__ will give the name of the class of an object.

Answered by: Arnold677 | Posted: 28-02-2022



Answer 3

I agree with Mr.Shark, but if you have an instance of a class, you'll need to use its __class__ member:

>>> class test():
...     pass
...
>>> a_test = test()
>>>
>>> a_test.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute '__name__'
>>>
>>> a_test.__class__
<class __main__.test at 0x009EEDE0>

Answered by: Emma754 | Posted: 28-02-2022



Answer 4

From Python 3.3 and onwards we can use __qualname__ field for both classes & functions.

It differs from __name__ field for nested objects like class defined in other class

>>> class A:
        class B:
            pass
>>> A.B.__name__
'B'
>>> A.B.__qualname__
'A.B'

which may be quite useful.

Further reading

Answered by: Oliver598 | Posted: 28-02-2022



Answer 5

In [8]: str('2'.__class__)
Out[8]: "<type 'str'>"

In [9]: str(len.__class__)
Out[9]: "<type 'builtin_function_or_method'>"

In [10]: str(4.6.__class__)
Out[10]: "<type 'float'>"

Or, as was pointed out before,

In [11]: 4.6.__class__.__name__
Out[11]: 'float'

Answered by: Sophia855 | Posted: 28-02-2022



Similar questions

python - How to make a class that acts like a string?

I have a context manager that captures output to a string for a block of code indented under a with statement. This context manager yields a custom result object which will, when the block has finished executing, contain the captured output. from contextlib import contextmanager @contextmanager def capturing(): "Captures output within a 'with' block." from cStringIO import StringIO ...


python class in string

I have name of class in string like: conf[0] = 'smtp_config' and i want to run method like: self.ui.smtp_config.setText("....") How can i do this in python? :)


python - Use class as string

This question already has answers here:


python - Find end of class in string

General description: Firstly: I need to create hundreds of modules that get data from an API. The modules will have similar structure for the most part, but some elements will vary (their methods for example). Secondly: Many of those modules will have to be edited later on (for example, change a method in a module). Therefor I created a program that: opens a module (in write...


Python use string value as class / part of code

is it possible to use a value of a string directly inside of the code as a class etc? I don't know to exactly describe what I want to do with words, so the pseudo code version is probably the best way to understand what's the issue. Here is the example: for node in itemdict.iterkeys(): nodeinfo = itemdict.get(node) if nodeinfo[4] == "node": #create new Links based on original nodeclass #Exa...


python - how to tell if a string is base64 or not

I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients. When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the jython programming language? I...


regex - Python Split String

Lets Say we have Zaptoit:685158:zaptoit@hotmail.com How do you split so it only be left 685158:zaptoit@hotmail.com


python - How do I store a string with a `"` in it?

I want to have a JSON object with the value of an attribute as a string with the character ". For example: { "Dimensions" : " 12.0" x 9.6" " } Obviously this is not possible. How do I do this? With Python.


python - String inside a string

BASE_URL = 'http://foobar.com?foo=%s' variable = 'bar' final_url = BASE_URL % (variable) I get this 'http://foobar.com?foo=bar' # It ignores the inside string. But i wanted something like this 'http://foobar.com?foo='bar'' Thanks for the answer. Can you help me out with almost the same problem: lst = ['foo', 'bar', 'foo bar'] [st...


python - How to write PNG image to string with the PIL?

I have generated an image using PIL. How can I save it to a string in memory? The Image.save() method requires a file. I'd like to have several such images stored in dictionary.


python - How to match a string of a certain length with a regex

For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found here. Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows: 8:a string =&gt; "a string" i1234e =&gt; 1234 l1:a1:be =&gt; ['a', 'b'] d1...


Python string find

I want to find a certain substring inside a string. The string is stored in a list of strings. How can i do it?


python - How do I test if a string exists in a Genshi stream?

I'm working on a plugin for Trac and am inserting some javascript into the rendered HTML by manipulating the Genshi stream. I need to test if a javascript function is already in the HTML and if it is then overwrite it with a new version, if it isn't then add it to the HTML. How do I perform a search to see if the function is already there?


Strip final 0 off a python string

#!/usr/bin/env python import os, sys, subprocess, time while True: print subprocess.call("xsel", shell=True); time.sleep(1); Takes an entry from the clipboard and prints it, every 1 second. Result: copied0 entry0 from0 clipboard0 I do not know why it returns the final 0, but it apparently stops me from using string strip (int has not strip), he...


Python String parse

Im working on a data packet retrieval system which will take a packet, and process the various parts of the packet, based on a system of tags [similar to HTML tags]. [text based files only, no binary files]. Each part of the packet is contained between two identical tags, and here is a sample packet: "&lt;PACKET&gt;&lt;HEAD&gt;&lt;ID&gt;&lt;ID&gt;&lt;SEQ&gt;&lt;SEQ&gt;&lt;FILENAME&gt;&lt;FI...


python - What's the best Django search app?


How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.


python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.


python - What is the best way to copy a list?

This question already has answers here:


python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...


How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?


ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...


python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.


python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?


python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top