Python空构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42884795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python empty constructor
提问by Narek Tarasyan
Is there any way to create an empty constructor in python. I have a class:
有没有办法在python中创建一个空的构造函数。我有一堂课:
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
now I initialize it like this:
现在我像这样初始化它:
p = Point(0, 5, 10)
How can I create an empty constructor and initialize it like this:
如何创建一个空的构造函数并像这样初始化它:
p = Point()
回答by Waxrat
class Point:
def __init__(self):
pass
回答by Shreyash S Sarnayak
As @jonrsharpe said in comments, you can use the default arguments.
正如@jonrsharpe 在评论中所说,您可以使用默认参数。
class Point:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
Now you can call Point()
现在你可以打电话 Point()
回答by William Pearsall
You can achieve your desired results by constructing the class in a slightly different manner.
您可以通过以稍微不同的方式构造类来实现您想要的结果。
class Point:
def __init__(self):
pass
def setvalues(x, y, z):
self.x = x
self.y = y
self.z = z
回答by PurpleJo
You should define the __init__()
method of your Point
class with optional parameters.
您应该使用可选参数定义类的__init__()
方法Point
。
In your case, this should work:
在您的情况下,这应该有效:
class Point:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
pointA = Point(0, 5, 10)
print("pointA: x={}, y={}, z={}".format(pointA.x, pointA.y, pointA.z))
# print "pointA: x=0, y=5, z=10"
pointB = Point()
print("pointB: x={}, y={}, z={}".format(pointB.x, pointB.y, pointB.z))
# print "pointB: x=0, y=0, z=0"