简体   繁体   English

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

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

I am trying to define a generic base class Geometry , with a unique id for each object starting at 0. I am using init as the method. 我试图定义一个通用基类Geometry ,每个对象的唯一ID从0开始。我使用init作为方法。

I am trying to create a generic base class named Geometry that I will use to organize geometry objects like point or polygon and containing an id attribute starting at 0. I know all of the objects should have a unique ID. 我正在尝试创建一个名为Geometry的通用基类,该类将用于组织诸如点或多边形之类的几何对象,并包含从0开始的id属性。我知道所有对象都应具有唯一的ID。 I'm using the constructor ( __init__ ) when creating a new Geometry object (integer). 创建新的Geometry对象(整数)时,我正在使用构造函数( __init__ )。 And would like for the base class to automatically assign the ID of the Geometry object. 并希望为基类自动分配Geometry对象的ID。

Current code: 当前代码:

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

I think I am on the right path but I am not positive. 我认为我走了正确的道路,但我并不乐观。 Should I have id = 0 above def__init__(self,id) ? 我是否应该在def__init__(self,id)之上def__init__(self,id) id = 0

Any guidance will be appreciated. 任何指导将不胜感激。

If the first line of your class is id = 0 then it becomes a class attribute and is shared by all instances of Geometry and all of its children. 如果您的类的第一行id = 0则它将成为类属性,并且由Geometry的所有实例及其所有子代共享。

Here is an example of using a class scoped variable: 这是使用类范围变量的示例:

#!/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

Something feels wrong about this, though I've not put my finger on it. 尽管我还没全力以赴,但还是有一点不对劲。

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

__init__ in python is invoked when you create an instance of that class 创建该类的实例时,将在python中调用__init__

circle = Geometry(1)

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

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