__初始化Python语法

__初始化Python语法,python,class,Python,Class,我为食物项目创建了一个类。我想知道为什么在def\uuu init\uuu(self,type)中有两个参数,但当我调用Food('Meat')时,我只传递一个参数。我想这是因为\uuuu init\uuuu在某种程度上是特殊的 class Food(object): def __init__(self, type): self.type = type def cook_food_item(self): if self.type == 'Mea

我为食物项目创建了一个类。我想知道为什么在
def\uuu init\uuu(self,type)
中有两个参数,但当我调用
Food('Meat')
时,我只传递一个参数。我想这是因为
\uuuu init\uuuu
在某种程度上是特殊的

class Food(object):

    def __init__(self, type):
        self.type = type

    def cook_food_item(self):
        if self.type == 'Meat':
            print 'Grill it!'
        elif self.type == 'Vegetable':
            print 'Boil it!'
        elif self.type == 'Dairy':
            print 'Churn it!'

hot_dog = Food('Meat')
hot_dog.cook_food_item()

类中的所有方法都将类实例作为其第一个参数传递,包括
\uuuu init\uuuu
。类中的其他方法也是如此:
def cook\u food\u item(self)

如果您有另一个方法接受实际的参数,您应该将该参数放在
self
之后,留下如下内容:

class Food(object):
    ...

    def eat_with(self, drink):
        print("Eating a " + self.type + " while drinking a " + drink)

>>> hot_dog = Food("hot dog")
>>> hot_dog.eat_with("coke")
Eating a hot dog while drinking a coke
在幕后,这是在做类似的事情


\uuuu init\uuuu
确实很特别,因为它是一个,尽管这不是它作为第一个参数接收
self
的原因。作为一个类方法可以做到这一点。每个方法都接收
self
作为第一个参数,由Python自动传递。我强烈建议您阅读Python基础知识,比如本例。

这里的
\uuuu init\uuu
没有什么特别之处

在Python中,有两种方法:绑定和未绑定。类中定义的方法通常是绑定的,它允许您编写
myobj.mymethod()
,而不是
MyClass.mymethod(myobj)
。未绑定方法没有
self
参数,其行为与常规函数类似

为了说明这一点,可以创建如下未绑定方法:

def myfunction(x):
    return x

class MyClass(object):
    def __init__(self):
        self.unbound = myfunction

    def bound(self, x):
        print('MyClass.bound called with', self)
        return x

myobj = MyClass()
print(myobj.unbound(42))
print(myobj.bound(42))

请注意,
myfunction
(因此,
myobj.unbound
)无法访问
self
,除非您显式传入它。所以一般来说,像
MyClass.bound
这样的绑定方法是编写类时的首选工具<代码>\uuuu init\uuuu也不例外。作为一个未绑定的方法,它不是很有用。

你读过基本类教程吗?离题:不要使用任何内置函数作为变量名。@这在方法参数中很重要。当您全局分配某个内容以覆盖内置内容(如
sum=a+b+c
def myfunction(x):
    return x

class MyClass(object):
    def __init__(self):
        self.unbound = myfunction

    def bound(self, x):
        print('MyClass.bound called with', self)
        return x

myobj = MyClass()
print(myobj.unbound(42))
print(myobj.bound(42))