Why don’t my subclass instances contain the attributes from the base class (causing an AttributeError when I try to use them)?

The subclass should be: class TypeTwoEvent(Event): def __init__(self, level=None, *args, **kwargs): super().__init__(*args, **kwargs) self.sr1 = level Because __init__ is overridden, the base class’ __init__ code will only run if it is explicitly requested. Despite its strange name, __init__ is not specially treated. It gets called automatically after the object is created; but otherwise it’s an … Read more

Dynamically create class attributes

You could do it without metaclasses using decorators. This way is a bit more clear IMO: def apply_defaults(cls): defaults = { ‘default_value1’:True, ‘default_value2’:True, ‘default_value3’:True, } for name, value in defaults.items(): setattr(cls, name, some_complex_init_function(value, …)) return cls @apply_defaults class Settings(object): pass Prior to Python 2.6 class decorators were unavailable. So you can write: class Settings(object): pass … Read more

python: What happens when class attribute, instance attribute, and method all have the same name?

Class attributes are accessible through the class: YourClass.clsattribute or through the instance (if the instance has not overwritten the class attribute): instance.clsattribute Methods, as stated by ecatmur in his answer, are descriptors and are set as class attributes. If you access a method through the instance, then the instance is passed as the self parameter … Read more

How to check if an object has an attribute?

Try hasattr(): if hasattr(a, ‘property’): a.property See zweiterlinde’s answer below, who offers good advice about asking forgiveness! A very pythonic approach! The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except … Read more

How to check if an object has an attribute in Python?

Try hasattr(): if hasattr(a, ‘property’): a.property See zweiterlinde’s answer below, who offers good advice about asking forgiveness! A very pythonic approach! The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except … Read more

React Js conditionally applying class attributes

The curly braces are inside the string, so it is being evaluated as string. They need to be outside, so this should work: <div className={“btn-group pull-right ” + (this.props.showBulkActions ? ‘show’ : ‘hidden’)}> Note the space after “pull-right”. You don’t want to accidentally provide the class “pull-rightshow” instead of “pull-right show”. Also the parentheses needs … Read more