简体   繁体   中英

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.

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. I'm using the constructor ( __init__ ) when creating a new Geometry object (integer). And would like for the base class to automatically assign the ID of the Geometry object.

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) ?

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.

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

circle = Geometry(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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