必填:http://idownvotedbecau.se/noattempt/
首先,欢迎来到 SO!您需要先尝试一下,然后再询问,因为我们不是来做您的工作的。
但是我的心情非常好,所以我只会帮助您了解您的宠物课程是如何构建的,以便您可以自己尝试,我会为您提供基本信息,以免用完整的术语列表让您不知所措,因为我觉得就像你是编程新手一样。
那么,让我们开始吧:
class Pet:
"""
Pretty straight forward, you create a new class named "Pet", it inherits nothing
(10secs of web searching will tell you how to inherit in python).
"""
def __init__(self, name, eats):
"""
This method is called a magic method and is called whenever you create an object
A.K.A when you do x = Pet("Cortex", "Cheese")
"""
# Here you define the properties of your object, your pet will have
# a name and what it eats.
self.name = name
self.eats = eats
为了方便起见,我没有在代码块中添加太多信息。
__init__ 魔法方法
当你调用(创建)一个类对象(这里是 Pet)时,这个方法会被自动调用并执行。
self 关键字
self 将成为您实现的每个类方法的第一个参数,它表示该类的当前实例。
自我与任何事物之间的点
嗯,这就是您在 Python 对象中访问事物的方式。
如果您的机器上安装了 IPython,我建议您打开它,因为它可以帮助您了解对象内部的内容。
class MyClass():
def __init__(self):
self.variable1 = "foo"
self.variable2 = "bar"
self._variable3 = "baz"
def get_variable3(self):
return self._variable3
如果您没有 IPython,请看以下屏幕截图:
在点后按制表符后,您可以看到对象内部的内容。你可以看到variable1、variable2和方法get_variable3。
a = MyClass()
a.variable1 # will return "foo"
a.variable2 # will return "bar"
a.get_variable3() # will return "baz"
如果您想知道为什么看不到 _variable3,那是因为我在它的名称前面添加了 _,它隐藏了它,这就是我创建一个查看它的方法的原因。
继承
我知道我说过我不会帮你继承,但我仍然在这里。
超短解释:
继承是从父类中获取所有内容并将其放入子类中。
如果我参加我之前创建的课程:
class MyChildClass(MyClass):
"""
This is how you specify inheritance, just put the parent class in the brackets
"""
pass # the keyword for "do literally nothing"
那么如果你创建这个类的一个实例,看看里面有什么:
是的,这是一样的,父类 (MyClass) 中的所有内容都放在子类中。
然而,这是没有用的。问题是您可以在子类中定义特定于它的方法:
这里我在子类中定义了两个方法。您可以看到我重新定义了get_variable3 以返回variable1(无论出于何种原因),这意味着调用此方法时MyChildClass 对象将返回“foo”(variable1 中的值),而MyClass 对象将返回“baz ”。
我还创建了一个全新的方法,它只存在于 MyChildClass 中而不存在于 MyClass 中。
在你的代码中你提到了dog.eat_cat(cat),从现在开始你就会明白这是dog对象内部的一个方法,它接受一个参数。
我不是最擅长解释事情,所以我希望这可以帮助你至少掌握基本知识。