Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does inheritance work for Attributes?

People also ask

What happens in attribute inheritance?

An inherited attribute is one that is inherited from a parent product class. You customize an inherited attribute domain by editing its definition at the subclass level. When you edit an inherited attribute definition, the changes propagate to all members of the subclass, including other subclasses under that subclass.

Can class attributes be inherited?

Objects are defined by classes, classes can inherit attributes and behavior from pre-existing classes. The resulting classes are known as derived classes or subclasses. A subclass “inherits” all the attributes (methods, etc) of the parent class.

What is attribute inheritance and why is it important?

Attribute inheritance is the property by which subtype entities inherit values of all attributes and instance of all relationships of the supertype. This is important because it makes it unnecessary to include supertype attributes or relationships redundantly with the subtypes.

Where does an inheritance search look for an attribute?

The whole point of a namespace tool like the class statement is to support name inheritance. In Python, inheritance happens when an object is qualified, and involves searching an attribute definition tree (one or more namespaces). Every time you use an expression of the form object.


When Inherited = true (which is the default) it means that the attribute you are creating can be inherited by sub-classes of the class decorated by the attribute.

So - if you create MyUberAttribute with [AttributeUsage (Inherited = true)]

[AttributeUsage (Inherited = True)]
MyUberAttribute : Attribute
{
   string _SpecialName;
   public string SpecialName
   { 
     get { return _SpecialName; }
     set { _SpecialName = value; }
   }
}

Then use the Attribute by decorating a super-class...

[MyUberAttribute(SpecialName = "Bob")]
class MySuperClass 
{
  public void DoInterestingStuf () { ... }
}

If we create an sub-class of MySuperClass it will have this attribute...

class MySubClass : MySuperClass
{
   ...
}

Then instantiate an instance of MySubClass...

MySubClass MySubClassInstance = new MySubClass();

Then test to see if it has the attribute...

MySubClassInstance <--- now has the MyUberAttribute with "Bob" as the SpecialName value.


Yes that is precisely what it means. Attribute

[AttributeUsage(Inherited=true)]
public class FooAttribute : System.Attribute
{
    private string name;

    public FooAttribute(string name)
    {
        this.name = name;
    }

    public override string ToString() { return this.name; }
}

[Foo("hello")]
public class BaseClass {}

public class SubClass : BaseClass {}

// outputs "hello"
Console.WriteLine(typeof(SubClass).GetCustomAttributes(true).First());

Attribute inheritance is enabled by default.

You can change this behavior by:

[AttributeUsage (Inherited = False)]