עבור לתוכן
View in the app

A better way to browse. Learn more.

HWzone

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

שני מופעים של מחלקה מתערבבים במילון שלהם ב python

Featured Replies

פורסם

שלום.

כאשר אני יוצר מחלקה ובתוכה הגדרתי init עם מילון ריק

אז כאשר אני יוצר 2 מופעים חדשים ,אני מצפה שמילון 1 ישאר כמו שהוא, ומילון 2 יהיה משהו בנפרד,אך הוא מערבב מילון 1, עם מילון של 2 (ואפילו דורס את הקיים )...

דרישות: mutable.

איפה הבעייה ?

https://www.dropbox.com/s/v705ft1qqbg0rw4/vec.py

פורסם

ב-init הגדרת את הפרמטר עם הערך הדיפולטי {}=dic. הקומפיילר לא יוצר את הערך הדיפולטי כל פעם שאתה קורא לפונקציה, אלא רק פעם אחת ברגע שהגדרת אותה. כל פעם שאתה קורא ל-init בלי פרמטר, הוא שם ב-dic את המילון הזה, ככה שלכל האובייקטים שנוצרים כך יש את אותו מילון.

אתה יכול לעשות משהו כזה במקום:

def __init__(self,dic=None):
if dic is None:
dic = {}
self.dic = dic

נערך על-ידי שניצל

פורסם

אויש. אני זוכר כשנפלתי על זה בפעם הראשונה. חשבתי שאני יוצא מדעתי... :s0927:

למען הבהירות, זה נכון לכל פונקציה ולכל פרמטר דיפולטי, לא רק init. וכל טיפוס mutable, לא רק מילון (לדוגמא רשימה ריקה [] ).

פורסם
  • מחבר

יש, סוף סוף.... זה עובד כמו גדול..

ממש עזרת לי להבין , ולהצליח...

וגם תודה ל ZELLIG על חידוד בעניין הפונקציות וכו'..

נערך על-ידי MACHINE-GUN

פורסם

if dic is None מתפרש בקלות גם כ:

if not dic

ובהתאם if dic בודק אם הוא לא ריק.

פורסם

זהירות, כי if not dlc יעבוד גם על מילון ריק, מה שעלול להחליף את המליון בצורה שתפתיע את המשתמש:


class X:
def __init__(self, adict=None):
if not adict: adict = {}
self.adict = adict

x1 = X(mydict)
# obviousy x1.adict is a new emtpy dict, as expected

mydict = {1:'one'}
x2 = X(mydict)
# as expected, x2.adict is mydict, therefore it contains has key 1 with value 'one'

mydict = {}
x3 = X(mydict)
mydict[1] = 'one'
# OOPS! x3.adict is NOT mydict! x3.adict is still empty!

אם תשתמש ב- if mydict is None אז הדוגמא השלישית תעבוד נכון

נערך על-ידי Zelig

פורסם
  • מחבר

השתמשתי לבסוף במה ש "שניצל " אמר , והחכמתי מדיבריכם

ארכיון

דיון זה הועבר לארכיון ולא ניתן להוסיף בו תגובות חדשות.

דיונים חדשים

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.