Python 简明教程

Python - Constructors

Python constructor 是类中的一个实例方法,每当创建类的新的对象时,它会自动调用。构造函数的作用是在声明对象后立即为实例变量赋值。

Python constructor is an instance method in a class, that is automatically called whenever a new object of the class is created. The constructor’s role is to assign value to instance variables as soon as the object is declared.

Python 使用一个特殊方法 init() 在声明对象后立即初始化该对象的实例变量。

Python uses a special method called init() to initialize the instance variables for the object, as soon as it is declared.

Creating a constructor in Python

init () 方法扮演构造函数的角色。它需要一个名为 self 的强制参数,该参数是对象引用。

The init() method acts as a constructor. It needs a mandatory argument named self, which is the reference to the object.

def __init__(self, parameters):
#initialize instance variables

init () 方法以及类中的任意实例方法有一个强制参数 self。然而,你可以将任何名称赋予第一个参数,不一定非得是 self。

The init() method as well as any instance method in a class has a mandatory parameter, self. However, you can give any name to the first parameter, not necessarily self.

Types of Constructor in Python

Python 有两种类型的构造函数 -

Python has two types of constructor −

  1. Default Constructor

  2. Parameterized Constructor

Default Constructor in Python

不接受除 self 以外任何参数的 Python 构造函数称为默认构造函数。

The Python constructor which does not accept any parameter other than self is called as default constructor.

Example

让我们在 Employee 类中定义构造函数来初始化 name 和 age 作为实例变量。然后我们就可以通过其对象访问这些属性。

Let us define the constructor in the Employee class to initialize name and age as instance variables. We can then access these attributes through its object.

class Employee:
   'Common base class for all employees'
   def __init__(self):
      self.name = "Bhavana"
      self.age = 24

e1 = Employee()
print ("Name: {}".format(e1.name))
print ("age: {}".format(e1.age))

它将生成以下 output

It will produce the following output

Name: Bhavana
age: 24

对于以上的 Employee 类,我们声明的每个对象都将有其实例变量 name 和 age 的相同值。要声明具有不同属性而不是默认属性的对象,请为 init () 方法定义参数。

For the above Employee class, each object we declare will have same value for its instance variables name and age. To declare objects with varying attributes instead of the default, define arguments for the init() method.

Parameterized Constructor

如果构造函数使用 self 以及多个参数定义,则称为参数化构造函数。

If a constructor is defined with multiple parameters along with self is called as parameterized constructor.

Example

在这个示例中, init () 构造函数有两个形式参数。我们声明具有不同值的 Employee 对象 −

In this example, the init() constructor has two formal arguments. We declare Employee objects with different values −

class Employee:
   'Common base class for all employees'
   def __init__(self, name, age):
      self.name = name
      self.age = age

e1 = Employee("Bhavana", 24)
e2 = Employee("Bharat", 25)

print ("Name: {}".format(e1.name))
print ("age: {}".format(e1.age))
print ("Name: {}".format(e2.name))
print ("age: {}".format(e2.age))

它将生成以下 output

It will produce the following output

Name: Bhavana
age: 24
Name: Bharat
age: 25

你还可以为构造函数中的形式化参数分配默认值,以便可以在有或没有传入参数的情况下实例化该对象。

You can also assign default values to the formal arguments in the constructor so that the object can be instantiated with or without passing parameters.

class Employee:
   'Common base class for all employees'
   def __init__(self, name="Bhavana", age=24):
      self.name = name
      self.age = age

e1 = Employee()
e2 = Employee("Bharat", 25)

print ("Name: {}".format(e1.name))
print ("age: {}".format(e1.age))
print ("Name: {}".format(e2.name))
print ("age: {}".format(e2.age))

它将生成以下 output

It will produce the following output

Name: Bhavana
age: 24
Name: Bharat
age: 25

Python - Instance Methods

除了 init () 构造函数以外,一个类中还可能定义一个或多个实例方法。带有一个形式参数 self 的方法称为实例方法,因为它是由特定的对象调用的。

In addition to the init() constructor, there may be one or more instance methods defined in a class. A method with self as one of the formal arguments is called instance method, as it is called by a specific object.

Example

在以下示例中,displayEmployee() 方法已被定义为一个实例方法。它返回调用该方法的 Employee 对象的 name 和 age 属性。

In the following example a displayEmployee() method has been defined as an instance method. It returns the name and age attributes of the Employee object that calls the method.

class Employee:
   def __init__(self, name="Bhavana", age=24):
      self.name = name
      self.age = age
   def displayEmployee(self):
      print ("Name : ", self.name, ", age: ", self.age)

e1 = Employee()
e2 = Employee("Bharat", 25)

e1.displayEmployee()
e2.displayEmployee()

它将生成以下 output

It will produce the following output

Name : Bhavana , age: 24
Name : Bharat , age: 25

可以随时添加、移除或修改类的属性和对象:

You can add, remove, or modify attributes of classes and objects at any time −

# Add a 'salary' attribute
emp1.salary = 7000
# Modify 'name' attribute
emp1.name = 'xyz'
# Delete 'salary' attribute
del emp1.salary

你可以使用以下函数来访问属性,而不是使用普通语句 −

Instead of using the normal statements to access attributes, you can use the following functions −

  1. The getattr(obj, name[, default]) − to access the attribute of object.

  2. The hasattr(obj,name) − to check if an attribute exists or not.

  3. The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.

  4. The delattr(obj, name) − to delete an attribute.

# Returns true if 'salary' attribute exists
print (hasattr(e1, 'salary'))
# Returns value of 'name' attribute
print (getattr(e1, 'name'))
# Set attribute 'salary' at 8
setattr(e1, 'salary', 7000)
# Delete attribute 'age'
delattr(e1, 'age')

它将生成以下 output

It will produce the following output

False
Bhavana

Python Multiple Constructors

如前所述,我们定义 init () 方法来创建构造函数。然而,与 C++ 和 Java 等其他编程语言不同,Python 不允许使用多个构造函数。

As mentioned earlier, we define the init() method to create a constructor. However, unlike other programming languages like C++ and Java, Python does not allow multiple constructors.

如果你尝试创建多个构造函数,Python 不会抛出错误,但只会考虑类中的最后一个 init () 方法。它的先前定义将被最后一个定义覆盖。

If you try to create multiple constructors, Python will not throw an error, but it will only consider the last init() method in your class. Its previous definition will be overridden by the last one.

但是,有一种方法可以在 Python 中实现类似的功能。我们可以根据传给 init () 方法的参数的类型或数量来重载构造函数。这样便允许单个构造函数方法基于提供参数来处理各种初始化场景。

But, there is a way to achieve similar functionality in Python. We can overload constructors based on the type or number of arguments passed to the init() method. This will allow a single constructor method to handle various initialization scenarios based on the arguments provided.

Example

以下示例演示如何实现类似于多个构造函数的功能。

The following example shows how to achieve functionality similar to multiple constructors.

class Student:
   def __init__(self, *args):
      if len(args) == 1:
         self.name = args[0]

      elif len(args) == 2:
         self.name = args[0]
         self.age = args[1]

      elif len(args) == 3:
         self.name = args[0]
         self.age = args[1]
         self.gender = args[2]

st1 = Student("Shrey")
print("Name:", st1.name)
st2 = Student("Ram", 25)
print(f"Name: {st2.name} and Age: {st2.age}")
st3 = Student("Shyam", 26, "M")
print(f"Name: {st3.name}, Age: {st3.age} and Gender: {st3.gender}")

如果我们运行以上代码,它将生成以下 output -

When we run the above code, it will produce the following output

Name: Shrey
Name: Ram and Age: 25
Name: Shyam, Age: 26 and Gender: M