장고처럼 instance 생성시 class 변수에 값 설정하기.



장고 예 : https://docs.djangoproject.com/en/1.6/intro/overview/#design-your-model


from django.db import models

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)   # class 변수

    # On Python 3: def __str__(self):
    def __unicode__(self):
        return self.full_name

class Article(models.Model):
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter)

    # On Python 3: def __str__(self):
    def __unicode__(self):
        return self.headline


>>> from news.models import Reporter, Article # Create a new Reporter. >>> r = Reporter(full_name='John Smith') # 요거 흉내내기...



** 부모 class (Test) 의 생성자 (__init__) 내부에서 클래스변수 존재여부 확인후, 존재하면 값 설정한다.

     주의 : 인스턴스변수가 없으면 클래스변수에서 찾는다

             (아래의 경우, self.student_name 가  instance 변수에 없으므로 class 변수 student_name 를 찾는다.)

class Test:
    def __init__(self,**name):
        for k , v in name.items():
            # print repr(k), repr(v)
            try:
                getattr(self, k)  # check if variable exist
            except Exception as excp:
                print excp
                pass   # pass if variable not exist
            else:
                setattr(self,k,v)   # 인스턴스변수 없으면 클래스변수에 값 설정함.
                print 'new val : self.' + k + ' = ',  getattr(self,k)
 
    def __str__(self):
        pass
         
    def __unicode__(self):
        pass
 
    def save(self):
        print 'save.. data'
        pass
 
 
class NewTest(Test):
    student_name =''   # 데이터 입력할 class 변수...
    def __str__(self):
        return "my student name == " + self.student_name



 
>>> tt = Test(name = 'AA', name2 = 'BB', name3 = 'CC')
Test instance has no attribute 'name2'
Test instance has no attribute 'name3'
Test instance has no attribute 'name'
>>> 
>>> tt3 = NewTest(student_name = 'YY')     ##  ... 성공...
new val : self.student_name =  YY
>>> 
>>> tt2 = NewTest(name = 'KKK')
NewTest instance has no attribute 'name'
>>> 







*** 추가 참고 

      http://blog.kevinastone.com/django-model-descriptors.html








Posted by 자유프로그램