2021-05-15 20:54

# python创建模块中的包时，怎么处理变量个数未知的情况

``````import os
import math
class Geometry(object):
def __init__(self):
pass
@property
def gtype(self):
return "gtUNKNOWN"

class Point(Geometry):
def __init__(self,x,y):
self._x=x
self._y=y

@property
def gtype(self):
return "gtPoint"

@property
def x(self):
return self._x
@x.setter
def x(self,v):
self._x=v

@property
def y(self):
return self._y
@y.setter
def y(self,v):
self._y=v

@property
def length(self):
return math.sqrt(self._x**2+self._y**2)

def __str__(self):
return "Point (%f,%f)"%(self._x,self._y)
def __repr__(self):
return self.__str__()

class Circle(Point):
def __init__(self,x,y,r):
Point.__init__(self,x,y)
self._r=r

@property
def area(self):
return math.pi*self._r*self._r

@property
def perimeter(self):
return 2*math.pi*self._r

@property
def gtype(self):
return "gtCircle"

@property
def r(self):
return self._r

@r.setter
def r(self,v):
if v>0:
self._r=v
else:
raise NameError()

def __str__(self):
return "Circle(%f,%f,%f)"%(self._x,self._y,self._r)
def __repr__(self):
return self.__str__()

class rectangle(Point):
def __init__(self,x,y,w,h):
Point.__init__(self,x,y)
self._w=w
self._h=h

@property
def gtype(self):
return "gtRectangle"

@property
def w(self):
return self._w
@w.setter
def w(self,v):
self._w=v

@property
def h(self):
return self._h
@h.setter
def h(self,v):
self._h=v

@property
def Perimeter(self):
return 2*self._w+2*self._h

@property
def area(self):
return self._w*self._h
def __str__(self):
return "Rectangle(%f,%f,%f,%f)"%(self._x,self._y,self._w,self._h)``````

``````class BROKENLINE(Geometry):
def __init__(self,x0,y0,x1,y1):
Geometry.__init__(self)
self._start=Point(x0,y0)
self._end=Point(x1,y1)

@property
def gtype(self):
return "gtBROKENLINE"

@property
def start(self):
return Point(self._start.x,self._start.y)
@start.setter
def start(self,v):
self._start.x=v.x
self._start.y=v.y

@property
def end(self):
return Point(self._end.x,self._end.y)
@end.setter
def end(self,v):
self._end.x=v.x
self._end.y=v.y

@property
def length(self):
return math.sqrt((self.end.x-self.start.x)**2+(self.end.y-self.start.y)**2)

def __str__(self):
return "BROKENLINE(%f,%f,%f,%f)"%(self._start.x,self._start.y,self._end.x,self._end.y)
def __repr__(self):
return self.__str__()``````
• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 1条回答默认 最新

• benbenli 2021-05-15 21:13
已采纳

def __init__(self,*args)

args 时以各tuple，然后你再函数体里面可以检测元素个数和访问元素。

点赞 评论