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

  • Home
  • SEARCH
  • 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 8417999
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T02:11:49+00:00 2026-06-10T02:11:49+00:00

I’m trying to create metaclass in Python (2.7) that will set arguments passed to

  • 0

I’m trying to create metaclass in Python (2.7) that will set arguments passed to object’s __init__ as object attributes.

class AttributeInitType(type):        
    def __call__(self, *args, **kwargs):
        obj = super(AttributeInitType, self).__call__(*args, **kwargs)
        for k, v in kwargs.items():
            setattr(obj, k, v)
        return obj

Usage:

class Human(object):
    __metaclass__ = AttributeInitType

    def __init__(self, height=160, age=0, eyes="brown", sex="male"):
        pass

man = Human()

Question: I want man instance to have defaults attributes set as in class’s __init__. How can I do it?

Update: I’ve came to even better solution that:

  • inspects __init__ method only once during class creation
  • does not override attributes that where (possibly) set by class’s real __init__

Here is the code:

import inspect
import copy

class AttributeInitType(type):
    """Converts keyword attributes of the init to object attributes"""
    def __new__(mcs, name, bases, d):
        # Cache __init__ defaults on a class-level
        argspec = inspect.getargspec(d["__init__"])
        init_defaults = dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
        cls = super(AttributeInitType, mcs).__new__(mcs, name, bases, d)
        cls.__init_defaults = init_defaults
        return cls

    def __call__(mcs, *args, **kwargs):
        obj = super(AttributeInitType, mcs).__call__(*args, **kwargs)
        the_kwargs = copy.copy(obj.__class__.__init_defaults)
        the_kwargs.update(kwargs)
        for k, v in the_kwargs.items():
            # Don't override attributes set by real __init__
            if not hasattr(obj, k):
                setattr(obj, k, v)
        return obj
  • 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-10T02:11:51+00:00Added an answer on June 10, 2026 at 2:11 am

    You would need to introspect the __init__ method and extract any default values from there. The getargspec function would be helpful there.

    The getargspec function returns (among others) a list of argument names, and a list of default values. You can combine these to find the default argument specification of a given function, then use that information to set attributes on the object:

    import inspect
    
    class AttributeInitType(type):        
        def __call__(self, *args, **kwargs):
            obj = super(AttributeInitType, self).__call__(*args, **kwargs)
            argspec = inspect.getargspec(obj.__init__)
            defaults = dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
            defaults.update(kwargs)
            for key, val in defaults.items():
                setattr(obj, key, val)
            return obj
    

    With the above metaclass you can omit any of the arguments and they’ll be set on the new instance, or you can override them by passing them in explicitly:

    >>> man = Human()
    >>> man.age
    0
    >>> man.height
    160
    >>> Human(height=180).height
    180
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create an if statement in PHP that prevents a single post
Basically, what I'm trying to create is a page of div tags, each has
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace

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.