如何访问基类中子类的“静态”字段?

时间:2014-02-24 16:17:54

标签: python python-2.7

如何在父类中引用子类的属性?

我想从类属性中设置一个对象属性:

class _CharField( models.CharField ):

    def __init__( self ):
        self.max_length = something.patterns_field[ 'max' ]


class EmailField(_CharField):   
    patterns_field = PATTERNS.EMAIL


class NameField(_CharField):
    patterns_field = PATTERNS.NAME

而不是 __ init __ 中的somethind我想要子类的类对象来设置子实例的字段。我可以在我的例子中使用self,但我认为这不太正确。

如何更改我的代码?

2 个答案:

答案 0 :(得分:1)

你应该在父类中包含c(尽管你不需要)

class C1:
    c=-1
    def output( self ):
        print self.c
        print C1.c

class C2( C1 ):
    c = "1"
    def C1output():
      print C1.c
      print self.c

c = C2()

c.output()

在您更新的问题中我认为这是答案

class _CharField( models.CharField ):
   def __init__( self ):
       #remember this calls with self as the child class 
       self.max_length = self.patterns_field[ 'max' ]
       #or for equivelent of EmailField.patterns_field (assuming you dont know EmailField) refer to self.__class__ 
       self.max_length = self.__class__.patterns_field[ 'max' ]
       #self.__class__ is the Class of the caller(in this case the child)

self非常适合用于读取静态变量,但如果它在类上发生了变化,则可能无法获得更新版本

例如

class _CharField( ):
   patterns_field = {"max":-1}
   def __init__( self ):
       #remember this calls with self as the child class 
       self.max_length1 = self.patterns_field[ 'max' ]
       #or for equivelent of EmailField.patterns_field (assuming you dont know EmailField) refer to self.__class__ 
       self.max_length2 = self.__class__.patterns_field[ 'max' ]
       #self.__class__ is the Class of the caller(in this case the child)'

class EmailField(_CharField):   
    patterns_field = {'max':16}


class NameField(_CharField):
    patterns_field = {'max':12}

c  = _CharField()
print c.max_length1 # prints -1
print c.max_length2 # prints -1
e = EmailField()
print e.max_length1 #prints 16
print e.max_length2 #prints 16

n=NameField()
print n.max_length1 #prints 12
print n.max_length2 #prints 12

答案 1 :(得分:1)

也许您可以使用以下方法

class Parent(object):
  def __init__(self):
    self.max_length = self._get_max_length()

  def _get_max_length(self):
    return None # or a value that would make more sense

class Child(object):
   def _get_max_length(self):
     return self.exact_value