python类将自身的实例添加到列表中

时间:2013-10-10 12:02:31

标签: python class object initialization

我有一个房间课。我希望每次使用该类创建对象时,对象都会被添加到所有房间的列表中。 房间类:

class Rooms:
    """Room class, takes type,days,  occupied or not and when it frees up"""
    def __init__(self, room_type, days, occupied, when_free):
        self.room_type = room_type
        self.days = days
        self.occupied = occupied
        self.when_free = arrow.get(when_free,'YYYY-MM-DD')

任何其他反馈也值得赞赏!

也不确定我是否应该在此创建新主题但是有可能在创建对象并将被占用的True传递给对象时,您不需要传递第4个变量,它会将其作为当前相反的日期?简而言之,如果没有第四个变量,它会传递arrow.get(str(arrow.utcnow()),'YYYY-MM-DD')而不是

弄明白我的第二个问题。我确实将 init 更改为:

def __init__(self, room_type, days, occupied, when_free=str(arrow.get(str(arrow.utcnow()),'YYYY-MM-DD'))):
        self.room_type = room_type
        self.days = days
        self.occupied = occupied
        self.when_free = arrow.get(when_free,'YYYY-MM-DD')

4 个答案:

答案 0 :(得分:3)

理想情况下,您希望房间列表的范围是您计划使用它的位置。不是房间本身的一部分。所以,如果你有一个房间的建筑物:

class Building():
    def __init__(self):
        self.rooms = []

b = Building()
b.rooms.append(Room(room_type, days, occupied, when_free))

该建筑只是一个例子。重要的部分是rooms.append()。这应该在您实际需要使用房间列表的地方声明和使用。

答案 1 :(得分:2)

我建议采用比the above稍微优雅和合乎逻辑的方式:

class Building(object):
    def __init__(self):
        self.rooms = []

class Room(object):
    def __init__(self, building=None)

        if building:
            building.rooms.append(self)
        self.building = building

b = Building()
r = Room(b)

这样,您不需要每次都致电b.rooms.append,现在它更符合OOP。

答案 2 :(得分:1)

我原以为你可以使用装饰器来装饰 __ init __ 方法,该装饰器将实例附加到列表中,以避免在实例注册时使 __ init __ 方法混乱。现在,如果要跟踪实例,只需要为每个类的init方法添加一个装饰器。类似的东西:

#!/usr/bin/env python3

import sys

class InstanceRegister:
    def __call__(self, init):
        def register(instance, *args, **kwargs):
            init(instance, *args, **kwargs)
            try :
                instance.__class__.__instances__
            except:
                instance.__class__.__instances__ = []
            instance.__class__.__instances__.append(instance)
        return register

class Room:
    """Room class, takes type,days,  occupied or not and when it frees up"""
    @InstanceRegister()
    def __init__(self, room_type, days, occupied, when_free):
        self.room_type = room_type
        self.days = days
        self.occupied = occupied
        self.when_free = arrow.get(when_free,'YYYY-MM-DD')

    def __str__(self):
        return "Room of type {:s}".format(self.room_type)



def main():
    r1 = Room('type_a', 1, True, '1999-12-30')
    r2 = Room('type_b', 2, True, '2000-12-30')
    r3 = Room('type_c', 3, True, '2001-01-30')
    for room in Room.__instances__:
        print("{:s}".format(room))
    return 0

if __name__ == '__main__':
    sys.exit(main())

有关Understanding Python Decorators in 12 Easy Steps!

的装饰器的更多信息

答案 3 :(得分:1)

可能只是为了使列表成为一个类变量:

class Room(object):
    rooms = []
    def __init__(self, room_type, days, occupied, when_free):
        self.room_type = room_type
        self.days = days
        self.occupied = occupied
        self.when_free = arrow.get(when_free,'YYYY-MM-DD')
        Room.rooms.append(self)

r = Room('x', 1,2, True)
Room.rooms
[<Room object at 0x00000000C6325550>]
r.rooms
[<Room object at 0x00000000C6325550>]

因为它是一个类变量,所以你可以通过任何类实例或类本身来实现它。

编辑过“房间”而不是“自我”,这更安全......