Python 2.7,定义了一个带有属性的基类,id带有init构造函数



我正在尝试定义一个通用基类Geometry,每个对象都有一个从0开始的唯一id。我使用init作为方法。

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

当前代码:

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

我认为我走在正确的道路上,但我并不乐观。我的id = 0应该高于def__init__(self,id)吗?

如有任何指导,我们将不胜感激。

如果类的第一行是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)

最新更新