小编sam*_*mpy的帖子

Python中的类是否需要__init__构造函数?

我读到构造函数就像传递给类的第一个参数一样,这对我来说很有意义,因为参数似乎是通过__init__方法传递给类的。例如,

class NewsStory(object):
    def __init__(self, guid, title, subject, summary, link):
        self.guid = guid
        self.title = title
        self.subject = subject
        self.summary = summary
        self.link = link

    def get_guid(self):
        return self.guid

    def get_title(self):
        return self.title

    def get_subject(self):
        return self.subject

    def get_summary(self):
        return self.summary

    def get_link(self):
        return self.link
firstStory = NewsStory('Globally Unique Identifier', \
    'first_title','first_subject','This is an example \
    sumary','example_link@something.com')

print firstStory.get_guid() # prints Globally Unique Identifier
Run Code Online (Sandbox Code Playgroud)

因此,当我“调用”该类时,是否将__init__方法中的参数传递给它?我是班上的新手,我读到的所有内容我都很难理解和混淆。谢谢!

编辑1

我发现这个问题有助于解释某些事情,例如newinit之间的区别,抱歉,我不知道如何添加链接,必须剪切和粘贴:__init__可以做什么,__new__不能呢?

python oop constructor initialization class

5
推荐指数
1
解决办法
1万
查看次数

如何检查if语句中的两个条件?

我有一个 if 语句,我需要检查多个条件。

例如:

if (a == 0 and b != 0 or c != 0)
{
    //do something
}
Run Code Online (Sandbox Code Playgroud)

实现这一目标最有效的方法是什么?

c if-statement conditional-statements

1
推荐指数
1
解决办法
2万
查看次数

在python中是否有另一种方法可以从除del key [value]之外的字典中删除键值对?

我有一个单独工作的函数,但当我尝试在另一个函数中使用它时引发一个关键错误.而不是尝试解释更大的上下文,我认为只更改del hand [letter]会更容易,这是引发错误的地方.在某些情况下,我可以将hand [letter]改为hand.get(letter,None),但我不能将它与del运算符一起使用,它会抛出错误.有任何想法吗?

hand = {'r': 2, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u':1}
word = 'rapture'

def update_hand(hand, word):
"""This function loops through letters, and if the letter is in the \
hand, it reduces the corresponding int value by one, until there is \
no longer that letter in the hand, then it deletes the key,value pair \
all together"""
    letters = set(word)
    for letter in letters:
        if letter in hand.keys():
            hand[letter] = …
Run Code Online (Sandbox Code Playgroud)

python dictionary

0
推荐指数
1
解决办法
73
查看次数