Jan 5, 2012

nested class (inner class) in python

Advantages of inner class:

  1. Logical grouping of classes: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
  2. Increased encapsulation: Consider two top-level classes A and B where B needs access to members of A that would otherwise be declared private. By hiding class B within class A A's members can be declared private and B can access them. In addition B itself can be hidden from the outside world.
  3. More readable, maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

The main advantage is organization. Anything that can be accomplished with inner classes can be accomplished without them.

outer class 不能访问 inner class 的名字,反之 Inner class 也不能访问 outer class 的名字?

django 中使用了 nested class
class Meta:

class Student(models.Model):
    id = models.IntegerField()
    class = models.CharField()
    ...

    class Meta:
        ordering = ["id"]
Model metadata is "anything that's not a field", such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class Meta to a model is completely optional.

具体机制:
Model 除了包含域外,还包含一些和类有关的性质(选项),比如以某一个域排序。为了把这些性质和域区分开,把它们置于嵌套类 Meta 中。该类的成员都是事先定义好的。不要自己定义。
在使用中,比如要排序,django 会判断 Student 类是否包含 Meta 名字,如果包含,又会具体判断是否包含ordering 性质。

0 comments: