2017-03-19 72 views
0

我目前正在嘗試簡單的python類示例。我有一個父類(人)和一個子類(聯繫人)。新對象正被前一個對象覆蓋

我用兩個不同的對象c1和c2實例化子類。 C2正在取代C1。我究竟做錯了什麼 ?

#!/bin/python3 

import time 
from time import sleep 

class Person (object): 
    id = 0 
    name = None 
    fields = {} 

    def __init__(self): 
     ctime = time.strftime("%Y-%m-%d %H:%M:%S") 
     self.fields.update({"create_time":ctime, 
          "write_time" :ctime}) 
     Person.id+=1 

    def check_keys (self,vals): 
     for k in vals: 
      if not k in self.fields.keys(): 
       raise Exception("Key %s doesnot exists"%k) 

    def update(self,*args,**kwargs): 
     vals = kwargs['vals'] 
     self.check_keys(vals) 
     self.fields.update(vals) 
     ctime = time.strftime("%Y-%m-%d %H:%M:%S") 
     self.fields.update({"write_time":ctime}) 

    def write(self,*args,**kwargs): 
     vals = kwargs['vals'] 
     self.check_keys(vals) 
     self.fields.update(vals) 

    def detail (self): 
     print ("Model Name is ",self.name) 
     for k,v in self.fields.items(): 
      print("key:",k," value:",v) 
     print ("#"*50) 

    def get_id(self): 
     return self.id 

class Contact (Person): 
    name="contact" 
    contact_id = 0 
    fields = { 
     'id':None, 
     'name':None, 
     'age':None, 
    } 

c1 = Contact() 
c1.update(vals={'name':'sijan','age':31,'id':c1.get_id()}) 
sleep(1) 
c1.update(vals={'name':'sijan Shs'}) 

print ("calling contact 2") 

c2 = Contact() 
c2.update(vals={'name':'Aurelia','age':32,'id':c2.get_id()}) 

print ("calling contact 1") 
c1.detail() 
print ("calling contact 1") 
c2.detail() 

下面是從過去的2 c1.detail輸出樣本()和c2.detail()

calling contact 1 
Model Name is contact 
key: id value: 2 
key: name value: Aurelia 
key: age value: 32 
key: create_time value: 2017-03-19 15:35:54 
key: write_time value: 2017-03-19 15:35:54 
################################################## 
calling contact 2 
Model Name is contact 
key: id value: 2 
key: name value: Aurelia 
key: age value: 32 
key: create_time value: 2017-03-19 15:35:54 
key: write_time value: 2017-03-19 15:35:54 
################################################# 

我相信它應該是:

calling contact 1 
Model Name is contact 
key: id value: 1 
key: name value: Sijan Shs 
key: age value: 31 
key: create_time value: 2017-03-19 15:35:53 
key: write_time value: 2017-03-19 15:35:54 
################################################## 
calling contact 2 
Model Name is contact 
key: id value: 2 
key: name value: Aurelia 
key: age value: 32 
key: create_time value: 2017-03-19 15:35:54 
key: write_time value: 2017-03-19 15:35:54 
################################################# 

我紡我的腦袋想要弄清楚發生了什麼事。如果我使用父類,它可以平滑運行(即預測的行爲,即不同的數據)。但是我很難理解爲什麼這個子類會這樣做?我錯過了一些東西?

UPDATE

什麼,我想實現的是:

我將有幾類和每個班級都會有自己獨特的領域,即forexample地址地址名稱。我怎樣才能實現這一點,而不添加字段字典給父母? 例

class Address(Person): 
    fields={ 
     'address':None 
    } 

非常感謝球員, 這是工作,

#!/bin/python3 

import time 
from time import sleep 

class Person (object): 
    id = 0 
    name = None 
    fields = {} 

    def __init__(self): 
     ctime = time.strftime("%Y-%m-%d %H:%M:%S") 
     self.fields.update({"create_time":ctime, 
          "write_time" :ctime}) 
     Person.id+=1 

    def check_keys (self,vals): 
     for k in vals: 
      if not k in self.fields.keys(): 
       raise Exception("Key %s doesnot exists"%k) 

    def update(self,*args,**kwargs): 
     vals = kwargs['vals'] 
     self.check_keys(vals) 
     self.fields.update(vals) 
     ctime = time.strftime("%Y-%m-%d %H:%M:%S") 
     self.fields.update({"write_time":ctime}) 

    def write(self,*args,**kwargs): 
     vals = kwargs['vals'] 
     self.check_keys(vals) 
     self.fields.update(vals) 

    def detail (self): 
     print ("Model Name is ",self.name) 
     for k,v in self.fields.items(): 
      print("key:",k," value:",v) 
     print ("#"*50) 

    def get_id(self): 
     return self.id 

class Contact (Person): 


    def __init__(self): 
     self.name="contact" 
     self.fields = { 
      'id':None, 
      'name':None, 
      'age':None 
     } 
     super(Contact,self).__init__() 


ca = Contact() 
ca.update(vals={'name':'sijan','age':31,'id':ca.get_id()}) 
sleep(1) 
ca.update(vals={'name':'sijan Shs'}) 
ca.detail() 

cb = Contact() 
cb.detail() 
cb.update(vals={'name':'Aurelia','age':32,'id':cb.get_id()}) 

print ("calling contact 1") 
ca.detail() 
print ("calling contact 2") 
cb.detail() 

回答

1

nameidfields是類成員,因此在創建從Person繼承的Contact的實例時,不會實例化新值。

你想要做的是爲聯繫人的每個新實例創建一組新的屬性名稱,ID,字段。

下面的代碼會這樣做。注意它是如何定義的ID,名稱,域是添加當它草簽的情況下(在__init__功能)

因爲每個人都有姓名,身份證,我沒有領域有啓動他們 的聯繫類也是如此。請參閱Contact類的定義,以獲得繼承的更清晰的實現。

#!/bin/python3 

import time 
from time import sleep 

class Person (object): 
    # id = 0 
    # name = None 
    # fields = {} 

    def __init__(self): 
     self.id = 0 
     self.name = None 
     self.fields = { 
      'id':None, 
      'name':None, 
      'age':None, 
     } 

     ctime = time.strftime("%Y-%m-%d %H:%M:%S") 
     self.fields.update({"create_time":ctime, 
          "write_time" :ctime}) 
     self.id+=1 

    def check_keys (self,vals): 
     for k in vals: 
      if not k in self.fields.keys(): 
       raise Exception("Key %s doesnot exists"%k) 

    def update(self,*args,**kwargs): 
     vals = kwargs['vals'] 
     self.check_keys(vals) 
     self.fields.update(vals) 
     ctime = time.strftime("%Y-%m-%d %H:%M:%S") 
     self.fields.update({"write_time":ctime}) 

    def write(self,*args,**kwargs): 
     vals = kwargs['vals'] 
     self.check_keys(vals) 
     self.fields.update(vals) 

    def detail (self): 
     print ("Model Name is ",self.name) 
     for k,v in self.fields.items(): 
      print("key:",k," value:",v) 
     print ("#"*50) 

    def get_id(self): 
     return self.id 

class Contact (Person): 
    def __init__(self): 
     super(Contact, self).__init__() 
     self.contact_id = 0 


c1 = Contact() 
c1.update(vals={'name':'sijan','age':31,'id':c1.get_id()}) 
# sleep(1) 
c1.update(vals={'name':'sijan Shs'}) 

print ("calling contact 2") 

c2 = Contact() 
c2.update(vals={'name':'Aurelia','age':32,'id':c2.get_id()}) 

print ("calling contact 1") 
c1.detail() 
print ("calling contact 1") 
c2.detail() 
+0

我做了一些改變,它似乎工作。你有什麼建議嗎 ?這是做正確的方法嗎? –

1

這是因爲你引用類變量,而不是實例變量。從docs

一般來說,實例變量是唯一的每個實例和類變量數據是由類的所有實例共享的屬性和方法:

class Dog: 
    kind = 'canine'   # class variable shared by all instances 

    def __init__(self, name): 
     self.name = name # instance variable unique to each instance 

相反,可以寫你的類如下:

class Person(object): 
     self.id = 0 
     self.name = None 
     self.fields = {} 

# rest of the class ... 

class Contact (Person): 
    self.name="contact" 
    self.contact_id = 0 
    self.fields = { 
     'id':None, 
     'name':None, 
     'age':None, 
    } 

# rest of the class ... 
+0

非常感謝。一般來說,實例變量是針對每個實例唯一的數據,而類變量是針對該類的所有實例共享的屬性和方法的。歡呼:) –

+0

事情是我想寫的創建和更新時間戳,但如果沒有初始化,值不更新。有什麼建議麼 ? –