Python中的构造函数 [英] Constructors in Python
问题描述
在为Python构造函数方法编写代码时,我需要帮助。
I need help in writing code for a Python constructor method.
此构造方法将采用以下三个参数:
This constructor method would take the following three parameters:
x, y, angle
这是一个例子吗?
推荐答案
class MyClass(object):
def __init__(self, x, y, angle):
self.x = x
self.y = y
self.angle = angle
构造函数总是作为称为 __ init __()
的函数编写的。它必须始终将对正在构造的实例的引用作为其第一个参数。这通常称为 self
。其余参数由程序员决定。
The constructor is always written as a function called __init__()
. It must always take as its first argument a reference to the instance being constructed. This is typically called self
. The rest of the arguments are up to the programmer.
第一行的对象
是超类,即这表示 MyClass
是 object
的子类。
The object
on the first line is the superclass, i.e. this says that MyClass
is a subclass of object
. This is normal for Python class definitions.
您可以使用 self访问实例的字段(成员)。
语法
这篇关于Python中的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!