Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I require an attribute on a class definition?

Is there a way to enforce a compile requirement for certain attributes on a class or interface implementation?

For example, let's say my application uses a series of static classes that contain const int resource values. I'd like to decorate the class in a Description attribute to describe its contents. In concept, I'd like to apply this attribute requirement to an interface, then each static class would implement it with its required Description. I could write a run-time check or a unit test to check compliance. But really a compile-time check would be best.

Is there such a thing?

like image 530
spoulson Avatar asked May 24 '10 17:05

spoulson


People also ask

How do you define a class attribute?

Inside a class, you should qualify all references to class attributes with the class name; for example, MyClass. attr1 . All references to instance attributes should be qualified with the self variable; for example, self.

How do I add an attribute to a class?

Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.

Can classes have attributes?

Classes contain characteristics called Attributes. We make a distinction between instance attributes and class attributes. Instance Attributes are unique to each object, (an instance is another name for an object). Here, any Dog object we create will be able to store its name and age.

Which method is used to display the attributes of a class?

Accessing the attributes of a classgetattr() − A python method used to access the attribute of a class. hasattr() − A python method used to verify the presence of an attribute in a class. setattr() − A python method used to set an additional attribute in a class.


1 Answers

No, there's nothing like this. Unit tests are the best you can do, as far as I'm aware.

If you can identify the classes automatically (by name, or some other attribute that the class is decorated with) then you can easily write a unit test for all the classes in an assembly.

like image 117
Jon Skeet Avatar answered Oct 10 '22 05:10

Jon Skeet