如何在Python中创建一个空类?
类是用户定义的蓝图或原型,从中创建对象。类可以被认为是用户定义的数据类型。通常,类包含称为类属性的数据成员和用于修改类属性的成员函数。但是你有没有想过如何定义一个空类,即一个没有成员和成员函数的类?
在Python中,如果我们编写如下内容,它会引发SyntaxError
。
# Incorrect empty class in
# Python
class Geeks:
输出:
File "gfg.py", line 5
^
SyntaxError: unexpected EOF while parsing
在Python中,使用空类pass
语句来编写。 pass
是Python中的一个特殊语句,它什么也不做。它仅用作虚拟语句。但是,也可以创建空类的对象。
例子:
# Python program to demonstrate
# empty class
class Geeks:
pass
# Driver's code
obj = Geeks()
print(obj)
输出:
Python还允许我们设置空类的对象的属性。我们还可以为不同的对象设置不同的属性。请参阅以下示例以更好地理解。
# Python program to demonstrate
# empty class
class Employee:
pass
# Driver's code
# Object 1 details
obj1 = Employee()
obj1.name = 'Nikhil'
obj1.office = 'GeeksforGeeks'
# Object 2 details
obj2 = Employee()
obj2.name = 'Abhinav'
obj2.office = 'GeeksforGeeks'
obj2.phone = 1234567889
# Printing details
print("obj1 Details:")
print("Name:", obj1.name)
print("Office:", obj1.office)
print()
print("obj2 Details:")
print("Name:", obj2.name)
print("Office:", obj2.office)
print("Phone:", obj2.phone)
# Uncommenting this print("Phone:", obj1.phone)
# will raise an AttributeError
输出:
obj1 Details:
Name: Nikhil
Office: GeeksforGeeks
obj2 Details:
Name: Abhinav
Office: GeeksforGeeks
Phone: 1234567889
Traceback (most recent call last):
File "gfg.py", line 34, in
print("Phone:", obj1.phone)
AttributeError: 'Employee' object has no attribute 'phone'