class
#类的名字应该用大写字母
class Employee:
#给一些定义
""" define a class for all employee
instances in a company ”””
#没啥内容就写pass
pass
#创建一个实体
variable_name = Employee()
|
Attributes
instance attributes 是每个实体都有自己的
# Provide attributes and assign values to the instances
emp1.firstName = "Maria"
emp1.lastName = "Rena"
emp1.basicSalary = 12000
emp1.allowance = 5000
class attributes belong to the class itself, and are thus shared among all instances of the class
如果先声明instant attribute,再声明class attribute。那不会覆盖原来的instant attribute。
但如果原来在类里声明了一个类attribute,在后面再修改,那原来的值确实会被覆盖
obj.__dict__返回【实体】和它的所有方法
class.__dict__返回【类】的所有方法和属性
|
Methods
instant method是自定义的
class Employee:
bonusPercent = 0.2
# Define an instance method that takes no arguments
def calculateBonus(self):
return self.salary * Employee.bonusPercent
如何更改bonusPercent的默认值?用类的调用来改
Employee.bonusPercent=0.3
Constructor & Destructor Method 是内置的建立和销毁函数
__init__,__del__,__str__
|
使用默认参数初始化实例
#这段代码有条件才执行,如果不执行的话这个实例四个attribute都不会有
def __init__ (self, first = None, last = None, salary = None, allowances = None):
if first!= None and last!= None and salary!= None and allowances!= None:
self.firstName = first
self.lastName = last
self.salary = salary
self.allowances = allowances
print("Object initialized with supplied values")
|
写入和加载obj
import _pickle as cpickle
class stock:
def __init__(self, name, lots):
self.name = name
self.lots = lots
def __str__(self):
return f’{self.name}=>{self.lots}'
#写入
s1 = stock("Apple",1500)
s2 = stock("Google",2000)
with open("s1.obj", "wb") as f:
cpickle.dump(s1/[s1,s2], f)
#加载
with open("s1.obj", "rb") as f:
s1 = cpickle.load(f)
print(s1)
with open("ss.obj", "rb") as f:
data = cpickle.load(f)
for each in data:
print(each)
|
self.variable和class.variable的区别
class employee:
count=5
def __init__(self,x):
self.x=x
self.count=self.count+1
print ("this method is executed")
print (self.count)
print (employee.count)
emp1=employee("John")
emp1.count+=1
print(emp1.count)
print(employee.count)
结果是6,5,7,5。self.variable显示的是这个obj自己当前的值,class.variable显示的是他们共用的初始值
|
|
|
JSON data(json,dict和obj可以互相转化)
#把obj放进json再取出来
import json
from json import JSONEncoder
class stock(object):
def __init__(self, name, lots):
self.name = name
self.lots = lots
def __str__(self):
return f’{self.name}=>{self.lots}'
class StockEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
s1 = stock("Apple",1500)
# encode Object it
s1Json = json.dumps(s1, cls=StockEncoder, indent=4)
‘’’
json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary.
‘’’
resultDict = json.loads(s1Json)
s1Obj = stock(**resultDict)
#json data写入/存储
with open("stockPrettyPrint.json", "w") as write_file:
json.dump(s1, write_file,cls=StockEncoder, indent=4)
with open("stockPrettyPrint.json", "r") as read_file:
s = json.load(read_file)
PrettyJson = json.dumps(s, indent=4, separators=(',', ': '), sort_keys=True)
#Json, Dictionary, object
import json
from json import JSONEncoder
class stock(object):
def __init__(self, name, lots):
self.name = name
self.lots = lots
def __str__(self):
return f'{self.name}=>{self.lots}’
class StockEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
def StockDecoder(obj):
if '__type__' in obj and obj['__type__'] =='stock':
return stock(obj['name'], obj['lots'])
return obj
s2Obj = json.loads('{"__type__": "stock", "lots":2000, "name": "Google"}', object_hook=StockDecoder)
with open("stockPrettyPrint.json", "w") as write_file:
json.dump([s2Obj], write_file,cls=StockEncoder, indent=4))
with open("stockPrettyPrint.json", "r") as read_file:
print("Read JSON file")
s = json.load(read_file)
for each in s:
each = stock(**each)
print(each)
|
JSON data(json,dict和obj是可以互转)
#把obj放进json再取出来
import json
from json import JSONEncoder
class stock(object):
def __init__(self, name, lots):
self.name = name
self.lots = lots
def __str__(self):
return f’{self.name}=>{self.lots}'
class StockEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
s1 = stock("Apple",1500)
# encode Object it
s1Json = json.dumps(s1, cls=StockEncoder, indent=4)
‘’’
json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary.
‘’’
resultDict = json.loads(s1Json)
s1Obj = stock(**resultDict)
#json data写入/存储
with open("stockPrettyPrint.json", "w") as write_file:
json.dump(s1, write_file,cls=StockEncoder, indent=4)
with open("stockPrettyPrint.json", "r") as read_file:
s = json.load(read_file)
PrettyJson = json.dumps(s, indent=4, separators=(',', ': '), sort_keys=True)
#Json, Dictionary, object
import json
from json import JSONEncoder
class stock(object):
def __init__(self, name, lots):
self.name = name
self.lots = lots
def __str__(self):
return f'{self.name}=>{self.lots}’
class StockEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
def StockDecoder(obj):
if '__type__' in obj and obj['__type__'] =='stock':
return stock(obj['name'], obj['lots'])
return obj
s2Obj = json.loads('{"__type__": "stock", "lots":2000, "name": "Google"}', object_hook=StockDecoder)
with open("stockPrettyPrint.json", "w") as write_file:
json.dump([s2Obj], write_file,cls=StockEncoder, indent=4))
with open("stockPrettyPrint.json", "r") as read_file:
print("Read JSON file")
s = json.load(read_file)
for each in s:
each = stock(**each)
print(each)
|
|