繁体   English   中英

Python 2.7,定义具有属性的基类,具有init构造函数的id

[英]Python 2.7, defining a base class with attributes, id with init constructor

我试图定义一个通用基类Geometry ,每个对象的唯一ID从0开始。我使用init作为方法。

我正在尝试创建一个名为Geometry的通用基类,该类将用于组织诸如点或多边形之类的几何对象,并包含从0开始的id属性。我知道所有对象都应具有唯一的ID。 创建新的Geometry对象(整数)时,我正在使用构造函数( __init__ )。 并希望为基类自动分配Geometry对象的ID。

当前代码:

class Geometry(object):
    def__init__(self,id):
        self.id = id

我认为我走了正确的道路,但我并不乐观。 我是否应该在def__init__(self,id)之上def__init__(self,id) id = 0

任何指导将不胜感激。

如果您的类的第一行id = 0则它将成为类属性,并且由Geometry的所有实例及其所有子代共享。

这是使用类范围变量的示例:

#!/usr/bin/env python2

class Geometry(object):
    # ident is a class scoped variable, better known as Geometry.ident
    ident = 0

    def __init__(self):
        self.ident = Geometry.ident
        Geometry.ident += 1

class Circle(Geometry):
    def __init__(self, radius):
        Geometry.__init__(self)
        self.radius = radius

    def __str__(self):
        return '<Circle ident={}, {}>'.format(self.ident, self.radius)

class Equilateral(Geometry):
    def __init__(self, sides, length):
        # super is another way to call Geometry.__init__() without
        # needing the name of the parent class
        super(Equilateral, self).__init__()
        self.sides = sides
        self.length = length

    def __str__(self):
        return '<Equilateral ident={}, {}, {}>'.format(self.ident,
            self.sides, self.length)


# test that ident gets incremented between calls to Geometry.__init__()
c = Circle(12)
e = Equilateral(3, 8)
f = Circle(11)

print c
assert c.ident == 0
print e
assert e.ident == 1
print f
assert f.ident == 2

尽管我还没全力以赴,但还是有一点不对劲。

class Geometry(object):
    def __init__(self,id=0):
        self.id = id

创建该类的实例时,将在python中调用__init__

circle = Geometry(1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM