Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7739063
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T08:25:36+00:00 2026-06-01T08:25:36+00:00

Look at this code: class MyClass(): # Why does this give me NameError: name

  • 0

Look at this code:

class MyClass():

    # Why does this give me "NameError: name 'self' is not defined":
    mySelf = self

    # But this does not?
    def myFunction(self):
        mySelf2 = self

Basically I want a way for a class to refer to itself without needing to name itself specifically, hence I want self to work for the class, not just methods/functions. How can I achieve this?

EDIT: The point of this is that I’m trying to refer to the class name from inside the class itself with something like self.class._name_ so that the class name isn’t hardcoded anywhere in the class’s code, and thus it’s easier to re-use the code.

EDIT 2: From what I’ve learned from the answers below, what I’m trying to do is impossible. I’ll have to find a different way. Mission abandoned.

EDIT 3: Here is specifically what I’m trying to do:

class simpleObject(object):
    def __init__(self, request):
        self.request = request

@view_defaults(renderer='string')
class Test(simpleObject):

    # this line throws an error because of self
    myClassName = self.__class__.__name__

    @view_config(route_name=myClassName)
    def activateTheView(self):
        db = self.request.db
        foo = 'bar'

        return foo
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T08:25:38+00:00Added an answer on June 1, 2026 at 8:25 am

    Note that self is not defined at the time when you want the class to refer to itself for the assignment to work. This is because (in addition to being named arbitrarily), self refers to instances and not classes. At the time that the suspect line of code attempts to run, there is as of yet no class for it to refer to. Not that it would refer to the class if there was.

    In a method, you can always use type(self). That will get the subclass of MyClass that created the current instance. If you want to hard-code to MyClass, that name will be available in the global scope of the methods. This will allow you to do everything that your example would allow if it actually worked. E.g, you can just do MyClass.some_attribute inside your methods.

    You probably want to modify the class attributes after class creation. This can be done with decorators or on an ad-hoc basis. Metaclasses may be a better fit. Without knowing what you actually want to do though, it’s impossible to say.

    UPDATE:

    Here’s some code to do what you want. It uses a metaclass AutoViewConfigMeta and a new decorator to mark the methods that you want view_config applied to. I spoofed the view_config decorator. It prints out the class name when it’s called though to prove that it has access to it. The metaclass __new__ just loops through the class dictionary and looks for methods that were marked by the auto_view_config decorator. It cleans off the mark and applies the view_config decorator with the appropriate class name.

    Here’s the code.

    # This just spoofs the view_config decorator.
    def view_config(route=''):
        def dec(f):
            def wrapper(*args, **kwargs):
                print "route={0}".format(route)
                return f(*args, **kwargs)
            return wrapper
        return dec
    
    # Apply this decorator to methods for which you want to call view_config with 
    # the class name. It will tag them. The metaclass will apply view_config once it 
    # has the class name. 
    def auto_view_config(f):
        f.auto_view_config = True
        return f
    
    class AutoViewConfigMeta(type):
        def __new__(mcls, name, bases, dict_):
            #This is called during class creation. _dict is the namespace of the class and
            # name is it's name. So the idea is to pull out the methods that need
            # view_config applied to them and manually apply them with the class name.
            # We'll recognize them because they will have the auto_view_config attribute
            # set on them by the `auto_view_config` decorator. Then use type to create
            # the class and return it.
    
            for item in dict_:
                if hasattr(dict_[item], 'auto_view_config'):  
                    method = dict_[item]
                    del method.auto_view_config # Clean up after ourselves.
                    # The next line is the manual form of applying a decorator.
                    dict_[item] = view_config(route=name)(method)  
    
            # Call out to type to actually create the class with the modified dict.
            return type.__new__(mcls, name, bases, dict_)
    
    
    class simpleObject(object):
        __metaclass__ = AutoViewConfigMeta 
    
    
    class Test(simpleObject):
    
        @auto_view_config
        def activateTheView(self):
            foo = 'bar'
    
            print foo
    
    if __name__=='__main__':
        t = Test()
        t.activateTheView()
    

    Let me know if you have any questions.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Take a look at this code: public class Test { public static void main(String...
take a look at this example code: public class Comment { private Comment() {
Please take a look at this code: template<class T> class A { class base
I have some code that behaves like this: class Base {}; class MyClass :
Look at the following code: class MyClass{ public: MyClass(){} MyClass(MyClass &&){} MyClass(const MyClass &){}
look at this code, <head> <meta http-equiv=Content-Type content=text/html; charset=utf-8 /> <script> function change() {
take a look at this code: $(document).ready(function() { document.getElementById(sliderId).onmousedown = sliderMouseDown; }); function sliderMouseDown()
Let's look at this code: IList<IHouseAnnouncement> list = new List<IHouseAnnouncement>(); var table = adapter.GetData();
There is some problem, i can't understand anyway. look at this code please <script
I want to statically allocate the array. Look at the following code, this code

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.