我目前正在尝试简单的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
#################################################
我正在试图找出出错的地方。如果我使用父类,它工作顺利(预测的行为,即不同的数据)。但是我很难理解为什么子类的表现方式呢?我错过了什么吗?
更新
我想要实现的目标是:
我将会有更多的类,每个类都有其唯一的字段,例如地址名称的地址。如何在不将字段字典添加到父级的情况下实现此目的? 示例
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()
答案 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 ...
答案 1 :(得分:1)
name
,id
,fields
是类成员,因此当Contact
的实例继承自Person
时,不会实例化新值。< / p>
您要做的是为Contact的每个新实例创建一组新的属性名称,id,字段。
以下代码就是这样做的。注意它如何定义在初始化时添加实例的id,name,字段(在__init__
函数中)
由于每个人都有姓名,身份证,字段,我不必启动它们 Contact类也是如此。请参阅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()