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 7623047
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T04:36:24+00:00 2026-05-31T04:36:24+00:00

Wishing to avoid a situation like this: >>> class Point: x = 0 y

  • 0

Wishing to avoid a situation like this:

>>> class Point:
x = 0
y = 0
>>> a = Point()
>>> a.X = 4 #whoops, typo creates new attribute capital x

I created the following object to be used as a superclass:

class StrictObject(object):
    def __setattr__(self, item, value):
        if item in dir(self):
            object.__setattr__(self, item, value)
        else:
            raise AttributeError("Attribute " + item + " does not exist.")

While this seems to work, the python documentation says of dir():

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

Is there a better way to check if an object has an attribute?

  • 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-05-31T04:36:26+00:00Added an answer on May 31, 2026 at 4:36 am

    Much better ways.

    The most common way is "we’re all consenting adults". That means, you don’t do any checking, and you leave it up to the user. Any checking you do makes the code less flexible in it’s use.

    But if you really want to do this, there is __slots__ by default in Python 3.x, and for new-style classes in Python 2.x:

    By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.

    The default can be overridden by defining __slots__ in a new-style class definition. The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

    Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. Attempts to assign to an unlisted variable name raises AttributeError. If dynamic assignment of new variables is desired, then add '__dict__' to the sequence of strings in the __slots__ declaration.

    For example:

    class Point(object):
        __slots__ = ("x", "y")
    
    point = Point()
    point.x = 5 # OK
    point.y = 1 # OK
    point.X = 4 # AttributeError is raised
    

    And finally, the proper way to check if an object has a certain attribute is not to use dir, but to use the built-in function hasattr(object, name).

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

Sidebar

Related Questions

I'm wishing I could do something like the following in SQl Server 2005 (which
I am a Javascript Junkie and wishing to test around some codes. new RegExp(user=
Coming from a ruby background, I'm wishing NSString had some convenient methods like the
I got the following code, wishing to wrap a group of strings nicely in
I'm wishing to figure out how many milliseconds a particular function uses. So I
My company unwittingly switched from cvs to subversion and now we're all wishing we
I'm trying to get the source attribute of all images withing a specific div
Let's consider following, simplified example: We have 2 tabs withing <rich:tabPanel switchType=ajax> , each
I have a class, Autodrop, that contains several methods , a.o. 'metadata', that call
Is it possible to grab an event, hold it in a class property, do

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.