Constructors in Python [closed]

2020-02-11 04:15发布

I need help in writing code for a Python constructor method.

This constructor method would take the following three parameters:

x, y, angle 

What is an example of this?

4条回答
来,给爷笑一个
2楼-- · 2020-02-11 04:32
class MyClass(SuperClass):
    def __init__(self, *args, **kwargs):
        super(MyClass, self).__init__(*args, **kwargs)
        # do initialization
查看更多
地球回转人心会变
3楼-- · 2020-02-11 04:35

Constructors are declared with __init__(self, other parameters), so in this case:

def __init__(self, x, y, angle):
    self.x = x
    self.y = y
    self.angle = angle

You can read more about this here: Class definition in python

查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-11 04:36
forever°为你锁心
5楼-- · 2020-02-11 04:40
class MyClass(object):
  def __init__(self, x, y, angle):
    self.x = x
    self.y = y
    self.angle = angle

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.

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.

You access fields (members) of the instance using the self. syntax.

查看更多
登录 后发表回答