Pythonic способ инициализировать (сложные) статические элементы данных

Это может быть достигнуто с помощью хранимых процедур и триггеров . Вы можете попробовать что-то вроде этого:

DELIMITER $

CREATE PROCEDURE `friendship_check`(IN fk_friend_one_id INT, IN fk_friend_two_id INT)
BEGIN
    IF fk_friend_one_id < fk_friend_two_id THEN
        SIGNAL SQLSTATE '45000'
           SET MESSAGE_TEXT = 'check constraint on friendship failed';
    END IF;
END$
DELIMITER ;


-- before insert trigger
DELIMITER $
CREATE TRIGGER `friendship_before_insert` BEFORE INSERT ON `Friendship`
FOR EACH ROW
BEGIN
    CALL friendship_check(new.fk_friend_one_id,new.fk_friend_two_id);
END$
DELIMITER ;

17
задан Roee Adler 17 May 2009 в 20:06
поделиться

3 ответа

You're right on all counts. data_member will be created once, and will be available to all instances of coo. If any instance modifies it, that modification will be visible to all other instances.

Here's an example that demonstrates all this, with its output shown at the end:

def generate_data():
    print "Generating"
    return [1,2,3]

class coo:
    data_member = generate_data()
    def modify(self):
        self.data_member.append(4)

    def display(self):
        print self.data_member

x = coo()
y = coo()
y.modify()
x.display()

# Output:
# Generating
# [1, 2, 3, 4]
15
ответ дан 30 November 2019 в 12:01
поделиться

As others have answered you're right -- I'll add one more thing to be aware of: If an instance modifies the object coo.data_member itself, for example

self.data_member.append('foo')

then the modification is seen by the rest of the instances. However if you do

self.data_member = new_object

then a new instance member is created which overrides the class member and is only visible to that instance, not the others. The difference is not always easy to spot, for example self.data_member += 'foo' vs. self.data_member = self.data_member + 'foo'.

To avoid this you probably should always refer to the object as coo.data_member (not through self).

14
ответ дан 30 November 2019 в 12:01
поделиться

The statement data_member = generate_data() will be executed only once, when class coo: ... is executed. In majority of cases class statements occur at module level and are executed when module is imported. So data_member = generate_data() will be executed only once when you import module with class coo for the first time.

All instances of coo class will share data_member and can access it by writing coo.data_member. Any changes made to coo.data_member will be immediately visible by any coo instance. An instance can have its own data_member attribute. This attribute can be set by typing self.data_member = ... and will be visible only to that instance. The "static" data_member can still be accessed by typing coo.data_member.

6
ответ дан 30 November 2019 в 12:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: