python基础第十八课--OOP简化数据结构初始化过程(小白piao分享)
程序员文章站
2022-03-08 11:55:02
...
在python编程的过程中经常会碰到需要编写很多的类,调用很多次__init__()方法。这样经常是的代码重复量非常之大。
有没有办法可以简化构造初始化的个数,减少代码量?当然可以!方法就是将所有的属性初始化赋值放在一个基类中完成。代码如下:
1、对一般参数:
class Struct:
_field = []
def __init__(self,*args):
if len(args) != len(self._field):
raise TypeError('please insert {} arguments,but {} were given'.format(len(self._field),len(args)))
else:
for name, value in zip(self._field,args):
setattr(self,name,value)
import math
class Stock(Struct):
_field = ['name','shares','price']
class Point(Struct):
_field = ['x','y']
class Circle(Struct):
_field = ['radius']
@property
def area(self):
return math.pi * self.radius ** 2
c = Circle(4.0)#此处会调用父类的构造函数
print(c.area)
2、添加关键字参数:
2.1 让关键字参数作为映射,只允许关键字参数名字是_fields中已有的参数名。
代码如下:
class Struct:
_field = []
def __init__(self,*args,**kwargs):
if len(args) > len(self._field):
raise TypeError('please insert {} arguments,but {} were given'.format(len(self._field),len(args)))
else:
for name, value in zip(self._field,args):
setattr(self,name,value)
for name in self._field[len(args) : ]:
setattr(self,name,kwargs.pop(name))#pop返回该键所对应的值,并将其从关键字表(kwargs)中删除;设置在底层字典中
#如果不存在该名称的键,会报错,而该名称必须是_field中有的名称
if kwargs:
raise TypeError('Invalid argument:{}'.format(','.join(kwargs)))
class Stock(Struct):
_field = ['name','share','price']
def prt(self):
print(self.name,self.share,self.price)
#此时,关键字参数只能选择列表中有的参数
s = Stock('小白piao',share = '1000',price = '999')
s.prt()#小白piao 1000 999
s = Stock('小白piao',share = '1000',hehe = '999')#hehe不存在
'''
Traceback (most recent call last):
File "F:/PycharmProjects/class_obj/class_one.py", line 317, in <module>
s = Stock('小白piao',share = '1000',呵呵 = '999')
File "F:/PycharmProjects/class_obj/class_one.py", line 306, in __init__
setattr(self,name,kwargs.pop(name))#pop返回该键所对应的值,并将其从关键字表(kwargs)中删除;设置在底层字典中
KeyError: 'price'
'''
2.2 想要添加不存在的关键字参数:
代码如下:
class Struct:
_field = []
def __init__(self,*args,**kwargs):
if len(args) != len(self._field):
raise TypeError('please insert {} arguments,but {} were given'.format(len(self._field),len(args)))
for name, value in zip(self._field,args):
setattr(self,name,value)
extra_args = kwargs.keys() - self._field
for name in extra_args:
setattr(self,name,kwargs.pop(name))
if kwargs:
raise TypeError('Duplicate values for {}'.format(','.join(kwargs)))
class Stock(Struct):
_field = ['name','share','price']
def prt(self):
print(self.__dict__)
sto = Stock('小白piao',100,99,hehe = '你是菜鸡!')
sto.prt()#{'name': '小白piao', 'share': 100, 'price': 99, 'hehe': '你是菜鸡!'}