• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python9种方法来生成新的对象

python 搞java代码 3年前 (2022-05-21) 13次浏览 已收录 0个评论

先定义一个类:

class Point: 
 def __init__(<a href="https://www.gaodaima.com/tag/self" title="查看更多关于self的文章" target="_blank">self</a>, x, y): 
  self.x = x 
  self.y = y

www#gaodaima.com来源gao!daima.com搞$代!码网搞代码

下面我们使用9种方法来生成新的对象:

<a href="https://www.gaodaima.com/tag/point" title="查看更多关于point的文章" target="_blank">point</a>1 = Point(1, 2) 
point2 = eval("{}({}, {})".format("Point", 1, 2)) 
point3 = globals()["Point"](1, 2) 
point4 = locals()["Point"](1, 2) 
point5 = getattr(sys.modules[__name__], "Point")(1, 2) 
point6 = copy.deepcopy(point1) 
point7 = point1.__class__(1, 2) 
point8 = type('Point', (Point, ), {})(1, 2)
point9 = types.new_class('Point', (Point, ), {})(1, 2)

PS: 需要导入sys和types模块·

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python9种方法来生成新的对象
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址