📅  最后修改于: 2020-10-25 03:34:08             🧑  作者: Mango
构造函数是一种特殊的方法(函数),用于初始化类的实例成员。
在C++或Java中,构造函数与其类具有相同的名称,但在Python对构造函数的对待不同。它用于创建对象。
构造函数可以有两种类型。
当我们创建此类的对象时,将执行构造函数定义。构造函数还验证对象是否有足够的资源来执行任何启动任务。
在Python,__init __()方法模拟该类的构造函数。在实例化类时调用此方法。它接受自关键字作为第一个参数,该参数允许访问类的属性或方法。
根据__init __()的定义,我们在创建类对象时可以传递任意数量的参数。它主要用于初始化类属性。每个类都必须具有一个构造函数,即使它仅依赖于默认构造函数也是如此。
请考虑以下示例来初始化Employee类属性。
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
# accessing display() method to print employee 1 information
emp1.display()
# accessing display() method to print employee 2 information
emp2.display()
输出:
ID: 101
Name: John
ID: 102
Name: David
当我们创建类的对象时,构造函数会被自动调用。考虑以下示例。
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)
输出:
The number of students: 3
当我们不想操纵值或仅以self为参数的构造函数时,使用非参数化的构造函数。考虑以下示例。
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
参数化的构造函数具有多个参数以及self。考虑以下示例。
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
输出:
This is parametrized constructor
Hello John
当我们不在类中包含构造函数或忘记声明它时,它将成为默认构造函数。它不执行任何任务,而是初始化对象。考虑以下示例。
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
输出:
101 Joseph
让我们看另一种情况,如果在类中声明两个相同的构造函数,会发生什么情况。
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()
输出:
The Second Constructor
在上面的代码中,对象st称为第二个构造函数,而两者都具有相同的配置。 st对象无法访问第一种方法。在内部,如果类具有多个构造函数,则该类的对象将始终调用最后一个构造函数。
注意: Python不允许构造函数重载。
下表中描述了该类中定义的内置函数。
SN | Function | Description |
---|---|---|
1 | getattr(obj,name,default) | It is used to access the attribute of the object. |
2 | setattr(obj, name,value) | It is used to set a particular value to the specific attribute of an object. |
3 | delattr(obj, name) | It is used to delete a specific attribute. |
4 | hasattr(obj, name) | It returns true if the object contains some specific attribute. |
class Student:
def __init__(self, name, id, age):
self.name = name
self.id = id
self.age = age
# creates the object of the class Student
s = Student("John", 101, 22)
# prints the attribute name of the object s
print(getattr(s, 'name'))
# reset the value of attribute age to 23
setattr(s, "age", 23)
# prints the modified value of age
print(getattr(s, 'age'))
# prints true if the student contains the attribute with name id
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print(s.age)
输出:
John
23
True
AttributeError: 'Student' object has no attribute 'age'
除了其他属性, Python类还包含一些内置的类属性,这些属性提供有关该类的信息。
下表列出了内置的类属性。
SN | Attribute | Description |
---|---|---|
1 | __dict__ | It provides the dictionary containing the information about the class namespace. |
2 | __doc__ | It contains a string which has the class documentation |
3 | __name__ | It is used to access the class name. |
4 | __module__ | It is used to access the module in which, this class is defined. |
5 | __bases__ | It contains a tuple including all base classes. |
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
输出:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__